原文来自: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 ): |
强调一下:函数里边的变量和脚本里边的变量之间是没有连接的。
3 | script, input_file = argv |
11 | def print_a_line(line_count, f): |
12 | print line_count, f.readline() |
14 | current_file = open (input_file) |
16 | print "First let's print the whole file: \n" |
18 | print_all(current_file) |
20 | print "Now let's rewind, kind of like a tape." |
24 | print "let's print three lines:" |
27 | print_a_line(current_line, current_file) |
29 | current_line = current_line + 1 |
30 | print_a_line(current_line, current_file) |
32 | current_line = current_line + 1 |
33 | print_a_line(current_line, current_file) |
文件保存为ex20.py,假设file为ex20_example.txt,内容为:
To all 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: |
3 | To all the people out there. |
4 | I say I don't like my hair. |
5 | I need to shave it off. |
7 | Now let's rewind, kind of like a tape. |
8 | Let's print three lines: |
9 | 1 To all the people out there. |
11 | 2 I say I don't like my hair. |
13 | 3 I need to shave it off. |
人生苦短,我用python~