1. print() · 顯示資料
print() 會把文字或變量數值輸出到控制台。文字必須放在引號內。如果用逗號分隔多個項目,Python 會在項目之間自動加入空格。
print("Welcome to S3 Fun Day")
student_name = "Jason"
print("Hello", student_name)
這段程式沒有 input(),所以直接按「執行」。
按「執行」後顯示結果。
在工作紙中: 用 print() 顯示歡迎語、飲品菜單、選擇結果和找續。
2. 變量 · 記住資料
變量是數值的名稱。變量名稱放在左邊,然後使用 =,數值放在右邊。之後可以重用變量名稱,不需要再次輸入原本的數值。
ticket_type = "student"
price = 20
print(ticket_type, "ticket: HK$", price)
這段程式已經在程式碼內設定 ticket_type 和 price,所以不用輸入。
按「執行」後顯示結果。
在工作紙中: 重要變量包括 drink、price、payment 和 change。
3. input() · 要求用戶輸入
input() 會暫停程式,等待用戶輸入內容。輸入的答案應該儲存在變量中。
ticket_type = input("Ticket type? ")
print("You chose", ticket_type)
⚠ 常見錯誤: 如果只寫 input(...),但沒有寫 ticket_type =,程式會提出問題,但不會記住答案。
4. int() / float() · 把文字轉換成數字
所有來自 input() 的內容一開始都是文字。使用 int() 處理整數,使用 float() 處理小數。
tickets = int(input("How many tickets? "))
price = 20
total = tickets * price
print("Total HK$", total)
規則: 飲品價格和整數付款可用 int();如果要接受 0.5 這類毫子數值,就要用 float()。
5. if / elif / else · 選擇路線
當程式需要作出選擇時,就使用 if。如果有另一個可能選擇,就使用 elif。所有未符合的情況,可交給 else 處理。
ticket_type = input("Ticket type? ")
if ticket_type == "student":
price = 20
elif ticket_type == "teacher":
price = 30
else:
price = 50
print("Please pay HK$", price)
⚠ 語法檢查: 每一行 if、elif 和 else 都需要冒號 :。下面屬於該分支的指令必須縮排。
6. 比較運算符 · 提出 True/False 問題
條件是會得出 True 或 False 的問題。使用 == 比較文字或數字是否相同;使用 >= 檢查金額是否足夠。
payment = 50
price = 30
if payment >= price:
print("Payment accepted")
else:
print("Not enough money")
這段程式已經設定 payment = 50 和 price = 30,所以不用輸入。
按「執行」後顯示結果。
在工作紙中: 付款部分的關鍵條件是 payment >= price。
7. and / or · 組合多個條件
and 代表兩個條件都必須成立。or 代表至少一個條件成立即可。
用 or 處理不同輸入寫法
ticket_type = input("Ticket type? ")
if ticket_type == "student" or ticket_type == "STUDENT":
price = 20
用 and 表示兩個檢查都重要
payment = int(input("Pay: "))
if payment >= price and payment == 50:
print("Accepted")
轉移到售賣機: 把 ticket_type 換成 drink,把門票價錢換成飲品價錢,並把門票付款換成投幣付款。