美文网首页Learn to Code
《笨办法学Python3》练习十三:实参,拆包,变量

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

作者: 雨开Ame | 来源:发表于2019-03-01 21:04 被阅读0次

    练习代码

    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类型,同上一节提到的情况。

    相关文章

      网友评论

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

        本文链接:https://www.haomeiwen.com/subject/iqbjuqtx.html