书中代码:
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
修改代码为:
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)
输出结果:
python ex13.py 1 2 3
附加题:
1、给你的脚本三个以下的参数。看看会得到什么错误信息。试着解释一下?
ValueError: not enough values to unpack (expected 4, got 3)
规定的参数不足时,系统报参数不足的错误
2、再写两个脚本,其中一个接受更少的参数,另一个接受更多的参数,在参数解包时给它们取一些有意义的变量名。
2.1、两个参数的脚本
from sys import argv
script, height, weight = argv
print("The script is called:", script)
print("Your height is :", height)
print("Your weight is:", weight)
输出结果:
2.2 四个参数脚本
from sys import argv
script, position1, position2, position3, position4 = argv
print("left on the map maybe say:", position1)
print("up on the map maybe say:", position2)
print("right on the map say:", position3)
print("down on the may say:", position4)
输出结果:
python ex13.2.py west north east south
3、将 raw_input 和 argv 一起使用,让你的脚本从用户手上得到更多的输入。
from sys import argv
script, a1, a2 = argv
input_1 = input("Your " + a1 + " is: ")
input_2 = input("Your " + a2 + " is: ")
print("Your input %s is: %s " % (a1, input_1))
print("Your input %s is: %s " % (a2, input_2))
输出结果:
python ex13.3.py age weight