笨办法学python习题13 参数、解包、变量
题目
from sys import argv
#argv 是所谓的“参数变量(argument variable)”
script,first,second,third = argv #将 argv 解包(unpack)
print("the script is called:" , script) #接受文件名
print("your first variable is:" ,first)
print("your second variable is:" ,second)
print("your third variable is:" ,third)
首次运行 没有输入参数,直接运行ex13.py,报错
ValueError: too many values to unpack (expected 4)
PS E:\4.学习案例\习题集\shixi> python ex13.py
Traceback (most recent call last):
File "ex13.py", line 4, in <module>
script,first,second,third = argv #将 argv 解包(unpack)
ValueError: not enough values to unpack (expected 4, got 1)
发现报错内容是没有足够的值去解包(需要4个,只有一个参数),当时不知道script是输出文件名,后面按照教程,添加了三个参数,成功输出
PS E:\4.学习案例\习题集\shixi> python ex13.py first 2nd 3rd
the script is called: ex13.py
your first variable is: first
your second variable is: 2nd
your third variable is: 3rd
想知道文件名算不算一个变量,就注释掉输出script一行,代码如下:
from sys import argv
#argv 是所谓的“参数变量(argument variable)”
script,first,second,third = argv #将 argv 解包(unpack)
#print("the script is called:" , script) #接受文件名
print("your first variable is:" ,first)
print("your second variable is:" ,second)
print("your third variable is:" ,third)
执行结果(只是没有执行输出script,实际上还是将文件名放在第一个参数上):
PS E:\4.学习案例\习题集\shixi> python ex13.py first 2nd 3rd
your first variable is: first
your second variable is: 2nd
your third variable is: 3rd
解包时删除script,执行代码:
from sys import argv
#argv 是所谓的“参数变量(argument variable)”
first,second,third = argv #将 argv 解包(unpack)
#print("the script is called:" , script) #接受文件名
print("your first variable is:" ,first)
print("your second variable is:" ,second)
print("your third variable is:" ,third)
执行结果
PS E:\4.学习案例\习题集\shixi> python ex13.py first 2nd
your first variable is: ex13.py
your second variable is: first
your third variable is: 2nd
测试发现,解包第一个参数就是文件名,与script无关,哈哈哈。
加分习题
将input 与argv一起使用,让你的脚本从用户手上得到更多使用。
刚开始是以为要将参数用input的方式输入,两者结合使用,但是尝试了好几次都失败了,后面看到有其他博主提到两者都是输入,argv是在脚本运行之前输入参数,input是在脚本运行过程中输入,并且输入的是可以是数值、字符串等
第一次尝试:
#习题13 参数、解包、变量
first = input("please input the first variable:")
second = input("please input the second variable:")
third = input("please input the third variable:")
from sys import argv
#argv 是所谓的“参数变量(argument variable)”
script,first,second,third = argv #将 argv 解包(unpack)
#print("the script is called:" , script) #接受文件名
print("your first variable is:" ,first)
print("your second variable is:" ,second)
print("your third variable is:" ,third)
执行结果:(跟我开始想法不一样,尴尬了)
PS E:\4.学习案例\习题集\shixi> python ex13.py first second third
please input the first variable:a
please input the second variable:c
please input the third variable:d
your first variable is: first
your second variable is: second
your third variable is: third