簡體   English   中英

如何修復while循環中的if語句?

[英]How can I fix the if statements in my while loops?

在我的while循環的if語句中,當用戶將verify_name設置為no時,我希望它循環返回以詢問公司名稱。 但是,如果用戶輸入將verify_name設置為no,它將重新循環到verify_name輸入。 我該如何解決這個問題,使它脫離循環並重新詢問公司名稱?

import time
while True:
    company_name = input("\nWhat is the name of your company? ")
    while True:
        verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
        if verify_name.lower() == "no":
            print("\nPlease re-enter your company name.")
            continue
        elif verify_name.lower() not in ('yes', 'y'):
            print("\nThis is an invalid response, please try again.")
            time.sleep(1)
            continue
        else:
            print("\nWelcome {}.".format(company_name))
            break
    else:
        continue

    break

決定在嵌套的while循環之外重新詢問公司名稱; 內部while循環應與驗證yes / no輸入有關。

while True:
    company_name = input("\nWhat is the name of your company? ")

    while True:
        verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
        verify_name = verify_name.lower()
        if verify_name not in {'yes', 'no', 'y', 'n'}:
            print("\nThis is an invalid response, please try again.")
            time.sleep(1)
            continue
        break

    if verify_name in {'y', 'yes'}:
        print("\nWelcome {}.".format(company_name))
        break

    else:
        print("\nPlease re-enter your company name.")   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM