建议ex11-14连起来学习,主要讲input
参数,拆包,变量
我们继续深入学习input()。在这一节,我们能用另一种 input 方法,传递变量给我们的脚本 ex13. py
创建ex13.py文件,然后敲键盘打以下内容并保存
from sys import argv
# read the WYSS section for how to run this
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 varialbe is:", third)
第一行,import,我们称为导入,从sys模块导入argv。argv 是一个参数变量,你可以在Idle里输入type(argv),可以看到,它的类型是list,列表。第三行,我们从argv取出4个变量,分别命名为script, first, second, third。(我们称之为unpack——拆包,想象argv是一个箱子,我们从里面取出4个参数, 不知道这么说形象不?)
What you should see
注意看,你要怎么运行 ex13. py。在命令行提示符cmd里,输入第一行和结果显示,注意路径,建议用pycharm,对着ex13.py右键,选open in terminal
C:\PycharmProjects\learnpythonthehardway>python ex13.py first 2nd 3rd
The script is called: ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third varialbe is: 3rd
换不一样的参数,再看看
C:\PycharmProjects\learnpythonthehardway>python ex13.py stuff things that
The script is called: ex13.py
Your first variable is: stuff
Your second variable is: things
Your third varialbe is: that
C:\PycharmProjects\learnpythonthehardway>python ex13.py apple orange grapefruit
The script is called: ex13.py
Your first variable is: apple
Your second variable is: orange
Your third varialbe is: grapefruit
实际上,我们只需要把first 2nd 3rd覆盖成任何你想输入的三样东西。
如果你没正确的输入,你会得到错误的信息
$ python ex13.py first 2nd
Traceback (most recent call last):
File "ex13.py", line 3, in script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 3)
这个错误是告诉我们,没有提供足够的参数给argv,程序里只给了first 和 2nd。
Study drills
1、试着给少于3个参数,看看错误信息
2、写一个比例子参数少的脚本和一个比例子参数多的脚本。
3、结合input和argv来从使用者那里获得更多的输入。别想太复杂。
4、记住模块。