Published 8月 13, 2018 by with 0 comment

習題13 - 參數, 解包和變量




用Notepad++打下列的程式碼,
另存為ex13.py.
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)

然後用Windows的cmd, 執行python打開它.(並在後面加了3個參數: 1st 2nd 3rd)
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW

C:\Users\Peter\Desktop\Python\LP3THW>python .\ex13.py 1st 2nd 3rd
The script is called: .\ex13.py
Your first variable is: 1st
Your second variable is: 2nd
Your third variable is: 3rd

C:\Users\Peter\Desktop\Python\LP3THW>

完成

sys 為內置模組(Module), argv 為參數變量(argument variable), 不能隨意修改.
我們來修改一下程式碼.
Line 3, 改為大寫, 但Line 5 -8所有相對應的參數也要改為大寫 (SCRIPT, AAA, BBB, CCC).
from sys import argv
# read the WYSS section, for how to run this
SCRIPT, AAA, BBB, CCC = argv

print ("The script is called:", SCRIPT)
print ("Your first variable is:", AAA)
print ("Your second variable is:", BBB)
print ("Your third variable is:", CCC)

結果,
C:\Users\Peter\Desktop\Python\LP3THW>python ex13.py aaa 12b ,ccc
The script is called: ex13.py
Your first variable is: aaa
Your second variable is: 12b
Your third variable is: ,ccc

C:\Users\Peter\Desktop\Python\LP3THW>



最初發表  /  最後更新: 2018.08.13  /  2018.08.13

0 comments:

張貼留言