LearnPython3theHardWay__Excercise 13 Parameters, Unpacking, Variables

建议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 <module> 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、记住模块。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值