1 回答
TA贡献2039条经验 获得超7个赞
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
添加回答
举报