2 回答

TA貢獻1829條經驗 獲得超13個贊
反轉您的測試,使它們基于>=、not==和不使用elif(這使得通過的第一個測試阻止任何其他測試執行),只是簡單的if. 現在,每個通過的測試都會按順序打印。
if key >= 5:
print("5 Golden Rings.")
if key >= 4:
print("4 Calling Birds.")
if key >= 3:
print("3 French Hens.")
if key >= 2:
print("2 Turtle Doves.")
if key >= 1:
print("1 Partridge in a Pear Tree.")

TA貢獻1845條經驗 獲得超8個贊
我所做的是反轉它們,以便它們從最大到最小打印,如果大于該數字,則將 == 設置為 >= 進行打印。
from sys import exit
key = int(input("Choose a Christmas Gift from 1 to 5!"))
if type(key) != type(0):
print("Please enter a number.")
exit()
if not (1 <= key <= 5):
print(key,"is an invalid number.")
exit()
if key >= 5:
print("5 Golden Rings.")
if key >= 4:
print("4 Calling Birds.")
if key >= 3:
print("3 French Hens.")
if key >= 2:
print("2 Turtle Doves.")
if key >= 1:
print("1 Partridge in a Pear Tree.")
但是,如果您想擴展它,請執行以下操作:
from sys import exit
key = int(input("Choose a Christmas Gift from 1 to 5!"))
if type(key) != type(0):
print("Please enter a number.")
exit()
if not (1 <= key <= 5):
print(key,"is an invalid number.")
exit()
gifts = ["1 partridge in a pair tree","2 turtle doves","etc..","etc..","etc.."]
printer = [print (val) for ind,val in enumerate (gifts) if ind >=key]
打印機通過使用列表理解來工作,這與所說的相同
for ind,val in enumerate(gifts):
if ind >= key:
print(val)
添加回答
舉報