-1

我正在学习如何在 while 循环中使用 continue 语句,并将此代码作为练习示例编写。我希望在打印最终消息之前得到一些“本科”、“研究生”和“博士”的回复。我可以通过 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
4

1 回答 1

0

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
于 2020-08-19T17:33:10.243 回答