exercise 13

2680 ワード

#    Python               
from sys import argv
# read the wyss section for how to run this
#   argv  “  (unpack)”
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 first 2nd 3rdコマンドでプログラムを実行します
練習する
  • Try giving fewer than three arguments to your script. See that error you get? See if you can explainit.
  • Write a script that has fewer arguments and one that has more. Make sure you give the unpackedvariables good names.
  • Combine input with argv to make a script that gets more input from a user. Don’t overthink it. Justuse argv to get something, and input to get something else from the user.
  • Remember that modules give you features. Modules. Modules. Remember this because we’ll needit later.

  • 答え
  • 入力コマンド:python ex13.py first 2nd次のエラーが発生します:
  • Traceback (most recent call last):
      File "ex13.py", line 3, in 
        script, first, second, third = argv
    ValueError: not enough values to unpack (expected 4, got 3)
    

    入力コマンド:python ex13.py first 2nd 3rd 4thで次のエラーが発生します.
    Traceback (most recent call last):
      File "ex13.py", line 3, in 
        script, first, second, third = argv
    ValueError: not enough values to unpack (expected 4, got 3)
    

    だから入力コマンドは変数の個数によって決めなければならないので、多すぎても少なすぎてもだめです.

  • コード1:
    from sys import argv
    apple, banana, orange, pear, pineapple = argv
    
    print("The first fruit is called", apple)
    print("The sceond furit is called", banana)
    print("The third fruit is called", orange)
    print("The fourth furit is called", pear)
    print("The fifth fruit is called", pineapple)
    

    コード2:
    from sys import argv
    bear, wolf, tigger = argv
    
    print("the bear is",bear)
    print("the wolf is",wolf)
    print("the tigger is",tigger)
    

  • コード:
    from sys import argv
    dog, cat = argv
    
    print("the dog is called",dog)
    print("the cat is called",cat)
    
    fish = input("input name:")
    print(f"the fish is called {fish}")
    

    問題の中ではあまり心配しないで、別々に使うべきだと言っています.
    小結:パラメータ、解包、変数・from sys import argv・はモジュールをインポートする役割であり、このモジュールの具体的な役割はコマンドラインに入力されたパラメータをパッケージ化し、script,first,second,third = argvで解包し、各変数に割り当てるべきである.コマンドラインに入力される最初のパラメータは、必ずファイル名です.