练习代码
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 variable is:", third)
Study Drills
- Try giving fewer than three arguments to your script. See that error you get? See if you can explain it.
PS D:\docs\pylearn\lpthw> python ex13.py 1 2
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)
你准备了四个变量,然而不是所有变量都被赋了值,所以会出错。
- Write a script that has fewer arguments and one that has more. Make sure you give the unpacked variables good names.
from sys import argv
script, first = argv
print("The script name is:", script)
print("The first arg name is:", argv)
from sys import argv
script, one, two, three, four, five = argv
print("The script name is:", script)
print("arg1 is:", one)
print("arg2 is:", two)
print("arg3 is:", three)
print("arg4 is:", four)
print("arg5 is:", five)
- Combine input with argv to make a script that gets more input from a user. Don’t overthink
it. Just use argv to get something, and input to get something else from the user.
from sys import argv
script, name = argv
game = input("Hello, {}! What is your favorite Nintendo game? ".format(name))
print(f"Me Too! I think {game} is the best game ever!")
- Remember that modules give you features. Modules. Modules. Remember this because we’ll need it later.
补充
-
argv
也是string
类型,同上一节提到的情况。
网友评论