假如今天我們要去遊樂園玩雲霄飛車,一到門口服務生就會幫我們測身高是否高於120公分,若高於120公分才可以玩。進去之後又會進入下一個判斷,年紀是否小於12歲?若小於12歲則收門票5元,若大於12歲小於等於18歲則需要7元,若是大於18歲則收12元。再來最後一個判斷是是否要拍照留念?若要的話再多加3元。
Ok照著上面的描述,我們可以來畫流程圖。如下
那程式怎麼寫呢? 很簡單:
print(“Welcome to the rollercoaster!”)
height = int(input(“What is your height in cm? “))
#Initialize the bill value
bill = 0
#the first if-else statement
if height >= 120:
print(“You can ride the rollercoaster!”)
age = int(input(“What is your age? “))
if age < 12:
bill = 5
print(“Child tickets are $5.”)
elif age <= 18:
bill = 7
print(“Youth tickets are $7.”)
elif age >= 45 and age <= 55:
print(“Everything is going to be ok. Have a free ride on us!”)
else:
bill = 12
print(“Adult tickets are $12.”)
wants_photo = input(“Do you want a photo taken? Y or N. “)
#the secondif-else statement
if wants_photo == “Y”:
bill = bill+3 #or bill += 3
print(f”Your final bill is ${bill}”)
else:
print(“Sorry, you have to grow taller before you can ride.”)
再來練習一個 Pizza 最後多少錢的問題
好我們假設價錢是由大中小(25元、20元、15元)和有沒有加義式香腸(大的加香腸要多3元,小的或中的要加2元)決定,那我們可以怎麼寫程式呢?
print(“Welcome to Python Pizza Deliveries!”)
size = input(“What size pizza do you want? S, M, or L “)
add_pepperoni = input(“Do you want pepperoni? Y or N “)
extra_cheese = input(“Do you want extra cheese? Y or N “)
bill = 0
#S->小, M->中,L->大
if size == “S”:
bill += 15
elif size == “M”:
bill += 20
else:
bill += 25
if add_pepperoni == “Y”:
if size == “S”:
bill += 2
else:
bill += 3
if extra_cheese == “Y”:
bill += 1
print(f”Your final bill is: ${bill}.”)
探討if 後面有大於兩個condition的情況
語法其實很簡單,形式就是下面那樣 :
if condition1 & condition2 & condition3:
do this
else:
do this
還記得第一個遊樂園的例子嗎?
我們在Age條件上再加一個Aged 45–55(年紀45歲到55歲的),一樣畫出流程圖如下。
照上面的流程打出code:
print(“Welcome to the rollercoaster!”)
height = int(input(“What is your height in cm? “))
bill = 0
if height >= 120:
print(“You can ride the rollercoaster!”)
age = int(input(“What is your age? “))
if age < 12:
bill = 5
print(“Child tickets are $5.”)
elif age <= 18:
bill = 7
print(“Youth tickets are $7.”)
elif age >= 45 and age <= 55:
print(“Everything is going to be ok. Have a free ride on us!”)
else:
bill = 12
print(“Adult tickets are $12.”)
wants_photo = input(“Do you want a photo taken? Y or N. “)
if wants_photo == “Y”:
bill += 3
print(f”Your final bill is ${bill}”)
else:
print(“Sorry, you have to grow taller before you can ride.”)