简体   繁体   中英

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

In the if statements of my while loops, I want it to loop back to ask for the company name when the user sets verify_name to no. However, if the user inputs sets verify_name to no, it re-loops to the verify_name input. How can I fix this so that it breaks out of this loop and re-ask the company 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

Make the decision to re-ask the company name outside of the nested while loop; the inner while loop should only be concerned with validating the yes/no input.

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.")   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM