while 循环中的 Python continue 语句问题

我正在学习如何在 while 循环中使用 continue 语句,并将此代码作为练习示例编写。我希望在打印最终消息之前得到一些“本科生”、“研究生”和“博士”的回复。我可以继续完成吗?


print("Welcome to Higher Education U. Please partake in the following roll call.")

name = input("What is your name? ")

level = input("Which program are you in: undergrad, grad, phd or other? ")


while True:

    if level == 'undergrad':

        print(f"Hi {name}, you are one of the first undergrads.")

        continue

    elif level == 'grad':

        print(f"Hi {name}, you are one of the first grad students.")

        continue

    elif level == 'phd':

        print(f"Hi {name}, you are one of the first phd students.")

        continue

    else:

        print(f"Hi {name}, please consider applying to HEU!")

        break


www说
浏览 132回答 1
1回答

largeQ

while当您到达缩进代码套件的末尾时,循环会自动继续,因此您的套件无需if手动执行。但是您需要将提示放在 中,while以便它在您进行时不断提示您输入更多数据。你的代码可能是print("Welcome to Higher Education U. Please partake in the following roll call.")while True:&nbsp; &nbsp; name = input("What is your name? ")&nbsp; &nbsp; level = input("Which program are you in: undergrad, grad, phd or other? ")&nbsp; &nbsp; if level == 'undergrad':&nbsp; &nbsp; &nbsp; &nbsp; print(f"Hi {name}, you are one of the first undergrads.")&nbsp; &nbsp; elif level == 'grad':&nbsp; &nbsp; &nbsp; &nbsp; print(f"Hi {name}, you are one of the first grad students.")&nbsp; &nbsp; elif level == 'phd':&nbsp; &nbsp; &nbsp; &nbsp; print(f"Hi {name}, you are one of the first phd students.")&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print(f"Hi {name}, please consider applying to HEU!")&nbsp; &nbsp; &nbsp; &nbsp; break对于多个值,您有相同的算法,您可以将它们放入一个容器中,并且只执行一次该算法。你想跟踪申请者的数量,所以记录名字的字典是有意义的。print("Welcome to Higher Education U. Please partake in the following roll call.")types = {"undergrad":[], "grad":[], "phd":[]}while True:&nbsp; &nbsp; name = input("What is your name? ")&nbsp; &nbsp; level = input("Which program are you in: undergrad, grad, phd or other? ")&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; normalized = level.casefold()&nbsp; &nbsp; &nbsp; &nbsp; types[normalized].append(name)&nbsp; &nbsp; &nbsp; &nbsp; if len(types[normalized]) < 3:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(f"Hi {name}, you are one of the first {level}s.")&nbsp; &nbsp; &nbsp; &nbsp; if min(len(names) for names in types.values()) > 3:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Classes full")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; except KeyError:&nbsp; &nbsp; &nbsp; &nbsp; print(f"Hi {name}, please consider applying to HEU!")&nbsp; &nbsp; &nbsp; &nbsp; break
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python