Python之路:函数和变量

 原文来自:http://www.yuanyong.org/blog/python/way-to-python-function-variable

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

 

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

pycharm

 

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,内容为:

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:
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~

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值