使用python的while語句,編寫簡單門票與年齡計算器

假設遊樂園或不同的景點會根據年齡收取不同的票價:
1.不到3歲的小孩免門票;
2.3歲到12歲的小孩需買兒童票,每張10元;
3.超過12歲的小孩及成人則需買成人票,每張20元;
4.大於60歲的老人,則可以買老年票,每張15元。


#首先在程序開頭可以先編寫好相對應提示語句,使顧客知道需要輸入什麼樣的內容:

prompt = "\nPlease enter your age."
prompt += "\n(You will know how much you should pay for the ticket):"

#接着就可以用while語句來編輯一個循環的語句。直接無限循環語句可用while true來執行:

while True:
    message = input(prompt)
    message = int(message)

input(): 將prompt內容先插入,提示用戶需要輸入內容,再進行輸入。
int(message) 則是在數值比較時不可缺。
#message裏輸出的值會是一個字符串。如果用戶將會輸入數字,而後又需將進行數字之間的對比,需要將message先轉化爲數值用int()函數
#用int()函數內部不能爲空,爲空則會無限循環第一個if語句。“之後無論輸入什麼值,都直接跳到You are free for the show!”


#最後則在while語句中嵌套一個if從句就可以了:

while True:
    .....
    .....

    if message < 3:
        print("\nYou are free for the show!")
    elif message <= 12:
        print("\nYou are a child, and only need 10 dollars for the show.")
    elif message <= 60:
        print("\nYou should pay for 20 dollars for this show.")
    else:
        print("\nYou have discount, and only need to pay 15 dollars.")

運行結果:
使用python的while語句,編寫簡單門票與年齡計算器

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章