《笨办法学Python3》练习十三:实参,拆包,变量

练习代码

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

  1. 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)

你准备了四个变量,然而不是所有变量都被赋了值,所以会出错。

  1. 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)
  1. 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!")
  1. Remember that modules give you features. Modules. Modules. Remember this because we’ll need it later.

补充

  1. argv也是string类型,同上一节提到的情况。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容