如何修复 while 循环中的 if 语句? [英] How can I fix the if statements in my while loops?

查看:57
本文介绍了如何修复 while 循环中的 if 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 while 循环的 if 语句中,我希望它在用户设置 verify_name 时循环返回以询问公司名称没有.但是,如果用户输入将 verify_name 设置为 no,它会重新循环到 verify_name 输入.我该如何解决这个问题,让它跳出这个循环并重新询问公司名称?

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

推荐答案

决定在嵌套的while循环之外重新询问公司名称​​outside;内部 while 循环应该关注验证是/否输入.

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

这篇关于如何修复 while 循环中的 if 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆