如何修复 while 循环中的 if 语句?

编程入门 行业动态 更新时间:2024-10-20 09:21:02
本文介绍了如何修复 while 循环中的 if 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在我的 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 03:25:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128981.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!