Learn Python the Hard Way 13 Parameters, Unpacking, Variables
更多傳入變數的方法
這次練習要來看看更多關於傳入變數的方法,我們稱這個概念為引數 (Argument),接下來會透過實例來說明,不過打好了程式碼先別急著跑。
from sys import argv
script, first, second, third = argvprint("The script is called", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
在第一行我們用了一個叫 import 的東西,整段話的意思是我們叫 sys 的組合包中匯入了一個叫 argv 的東西,這個名為 argv 的東西我們稱他為模塊 (modules),也有人叫他們做 libraries。Python 讓我們選擇我們要匯入什麼 module,避免把全部的 module 都給我們造成程式大太。除了程式大小的問題,其他工程師透過看我們匯入什麼 module,就有種看文件檔的感覺,能夠對我們之後程式碼做的事情有些基礎的了解。
我們匯入的 argv 是 argument variable,這個變數存有當我們跑 Python 腳本時的引數。光用看得可能很難想像他在幹嘛,我們繼續看第二行,我們把存在變數中的引數分成 4 個,於是我們可以把他們依順序,分別指派給不同的變數 script, first, second, third。
接下來要跑這個腳本了,這次的比較不一樣,我們要在 Terminal 輸入:
python ex13.py first 2nd 3rd
這樣我們會得到輸出:
output:
The script is called ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3rd
再來改變一下傳入的引數,這次改成輸入
python ex13.py I Love You
output:
The script is called ex13.py
Your first variable is: I
Your second variable is: Love
Your third variable is: You
再來
python ex13.py Fire Water Wind
output:
The script is called ex13.py
Your first variable is: Fire
Your second variable is: Water
Your third variable is: Wind
假設我們傳進來的引數不夠,傳這樣的話
python ex13.py first
就會得到 output:
Traceback (most recent call last):
File "ex13.py", line 2, in <module>
script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 2)
這樣就能大概了解 argv 是在做什麼了。
這系列文章的練習,都是來自於 Learn Python the Hard Way 這本書中,內容只針對練習做紀錄和自己的心得分享,為保護著作權故沒有透露太多內容,能力可及的話還是鼓勵大家買一本來自行練習,有問題都可以在下方進行討論。
Learn Python the Hard Way 系列文章
- LPTHW 01 First Program
- LPTHW 02 Comments & Pound Characters
- LPTHW 03 Numbers & Math
- LPTHW 04 Variables &Names
- LPTHW 05 More Variables & Printing
- LPTHW 06 Strings and text
- LPTHW 07 More Printing
- LPTHW 08 Printing, Printing
- LPTHW 09 Printing, Printing, Printing
- LPTHW 10 What Was That ?
- LPTHW 11 Ask Questions
- LPTHW 12 Prompting People
- LPTHW 13 Parameters, Unpacking, Variables