您的位置:首页 > 编程语言 > Python开发

Python之路:函数和变量

2013-09-20 19:52 225 查看
原文来自:http://www.yuanyong.org/blog/python/way-to-python-function-variable

我知道我写的一些代码至今仍然在运行,我觉得这是一个令人欣慰的贡献。

最近发觉windows下一个非常不错的python IDE,自带的IDLE实在是太烂了,用着真心崩溃,pycharm真心不错,windows下python IDE不二选择。



python函数是用来执行一个单一的,有关行动的有组织的,可重用代码块。功能提供了更好地为您的应用程序和代码重用的高度模块化。

Python为提供了许多内置功能,如print()等,但用户也可以创建自己的函数,这些功能被称为用户定义的函数。

Python定义函数的简单规则为:

①功能块函数名和括号

②关键字def开始

③函数的第一个语句可以是一个可选的声明 - 文档字符串的函数或的docstring

④在每个函数的代码块开始用冒号(: ) 和缩进

⑤语句返回

语法:

1
def
functionname(
parameters ):
2
function_docstring"
3
function_suite
4
return
[expression]
强调一下:函数里边的变量和脚本里边的变量之间是没有连接的。

1
from
sys
import
argv
2
3
script,
input_file
=
argv
4
5
def
print_all(f):
6
print
f.read()
#读入整个文件,并打印出来
7
8
def
rewind
(f):
9
f.seek(
0
)
#
指针指向文件开始的位置
10
11
def
print_a_line(line_count,
f):
12
print
line_count,
f.readline()
#读入行,并打印出来
13
14
current_file
=
open
(input_file)
15
16
print
"First
let's print the whole file: \n"
17
18
print_all(current_file)
19
20
print
"Now
let's rewind, kind of like a tape."
21
22
rewind(current_file)
#
经过print_all后指针指向文件末尾,故要重新设定到文件开始位置
23
24
print
"let's
print three lines:"
25
26
current_line
=
1
27
print_a_line(current_line,
current_file)
28
29
current_line
=
current_line
+
1
30
print_a_line(current_line,
current_file)
31
32
current_line
=
current_line
+
1
33
print_a_line(current_line,
current_file)
文件保存为ex20.py,假设file为ex20_example.txt,内容为:

Toall the people out there.

I say I don't like my hair.

I need to shave it off.

cmd后进入相应目录,运行“python ex20.py ex20_example.txt”,得下面结果:

1
First
let's
print
the
whole file:
2
3
To
all
the
people out there.
4
I
say I don't like my hair.
5
I
need to shave it off.
6
7
Now
let's rewind, kind of like a tape.
8
Let's
print
three
lines:
9
1
To
all
the
people out there.
10
11
2
I
say I don't like my hair.
12
13
3
I
need to shave it off.
人生苦短,我用python~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python