1 回答

TA貢獻2039條經驗 獲得超8個贊
while當您到達縮進代碼套件的末尾時,循環會自動繼續,因此您的套件無需if手動執行。但是您需要將提示放在 中,while以便它在您進行時不斷提示您輸入更多數據。
你的代碼可能是
print("Welcome to Higher Education U. Please partake in the following roll call.")
while True:
name = input("What is your name? ")
level = input("Which program are you in: undergrad, grad, phd or other? ")
if level == 'undergrad':
print(f"Hi {name}, you are one of the first undergrads.")
elif level == 'grad':
print(f"Hi {name}, you are one of the first grad students.")
elif level == 'phd':
print(f"Hi {name}, you are one of the first phd students.")
else:
print(f"Hi {name}, please consider applying to HEU!")
break
對于多個值,您有相同的算法,您可以將它們放入一個容器中,并且只執行一次該算法。你想跟蹤申請者的數量,所以記錄名字的字典是有意義的。
print("Welcome to Higher Education U. Please partake in the following roll call.")
types = {"undergrad":[], "grad":[], "phd":[]}
while True:
name = input("What is your name? ")
level = input("Which program are you in: undergrad, grad, phd or other? ")
try:
normalized = level.casefold()
types[normalized].append(name)
if len(types[normalized]) < 3:
print(f"Hi {name}, you are one of the first {level}s.")
if min(len(names) for names in types.values()) > 3:
print("Classes full")
break
except KeyError:
print(f"Hi {name}, please consider applying to HEU!")
break
添加回答
舉報