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

萝らか妹 提交于 2019-12-11 15:43:39

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/45804495/how-can-i-fix-the-if-statements-in-my-while-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!