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

Learn Python The Hard Way学习(13) - 参数,解包,变量

2012-06-19 13:59 567 查看
下面的练习我们将传递一个变量给脚本,你知道为什么你输入python ex13.py去执行ex13.py文件吗?在命令后面的ex13.py其实是一个“参数”,我们下面写一个能接受参数的脚本。
from sys import argv

script, first, second, third = argv

print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third


在第一行我们看到了“import”,这是从python功能库中导入功能的方法,不是导入所有的功能,而是导入你想导入的,这样能保持程序的简洁,方便其他程序员阅读。

argv是“参数变量”,一个非常标准的变量名,在其他程序语言中也能看到。这个变量保存了你运行脚本时的所有参数。

第3行的作用是解包变量argv,分别分配给四个变量:script,first,second,third。

等一下,特征还有另外一个名字
“features"真正的名称是:modules。当然也有人叫”libraries“,不过我们就叫模块吧。

运行结果
不同的运行参数会产生不同的结果。

root@he-desktop:~/mystuff# python ex13.py first 2nd 3nd
The script is called: ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3nd
root@he-desktop:~/mystuff# python ex13.py cheese apples bread
The script is called: ex13.py
Your first variable is: cheese
Your second variable is: apples
Your third variable is: bread
root@he-desktop:~/mystuff# python ex13.py Zed A. Shaw
The script is called: ex13.py
Your first variable is: Zed
Your second variable is: A.
Your third variable is: Shaw

你可以任意改变后面的三个参数值。但是如果你只输入了两个参数,那么会报如下的错误:

Traceback (most recent call last):
File "ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: need more than 3 values to unpack

就是提示你参数的个数不满足3个。

加分练习
1. 尝试输入少于3个参数,看看错误是什么样的?
错误如上

2. 写一个更少参数的脚本和一个更多参数的脚本,给解包的变量一个好理解的名字。

3. 结合raw_input和argv写一个脚本。
from sys import argv

script, first = argv

print "How %s are your?" % first
write = raw_input()
print "Your %s is %s." % (first, write)


输出:

root@he-desktop:~/mystuff# python ex13.py old
How old are your?
25
Your old is 25.

4. 记住modules为我们提供功能,稍后会用到。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: