1 回答

TA貢獻1818條經驗 獲得超11個贊
你的意思是這樣的嗎?第一個if檢查是否pay是"no"并跳過其余的代碼。下的所有elif pay == "yes":內容僅在payis 時執行"yes"。
if pay == "no":
discount = 0
elif pay == "yes":
if 100 <= firstBill < 200:
discount = (firstBill * 0.015)
elif 200 <= firstBill < 400:
discount = (firstBill * 0.03)
elif 400 <= firstBill < 800:
discount = (firstBill * 0.04)
elif firstBill >= 800:
discount = (firstBill * 0.05)
else:
print("error")
else:
print("error")
順便說一下,您可以鏈接比較運算符,例如x < y < z. 此外,您的代碼會為 EXACTLY 200 或 EXACTLY 400 等打印“錯誤”。我假設這是無意的并修復了它。
您還可以以不同的方式編寫 if 語句:
if pay == "yes":
if 100 <= firstBill < 200:
discount = (firstBill * 0.015)
elif 200 <= firstBill < 400:
discount = (firstBill * 0.03)
elif 400 <= firstBill < 800:
discount = (firstBill * 0.04)
elif firstBill >= 800:
discount = (firstBill * 0.05)
else:
print("error")
elif pay == "no":
discount = 0
else:
print("error")
它的工作原理完全相同。
添加回答
舉報