亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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條經驗 獲得超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


查看完整回答
反對 回復 2023-06-06
  • 1 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號