为了账号安全,请及时绑定邮箱和手机立即绑定

while 循环中的 Python continue 语句问题

while 循环中的 Python continue 语句问题

www说 2023-06-06 17:39:18
我正在学习如何在 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
查看完整描述

1 回答

?
largeQ

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


查看完整回答
反对 回复 2023-06-06
  • 1 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信