You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中实现循环:输入No时回到初始问题

如何用Python实现循环,让用户输入No时回到初始问题?

我周末一直在学Python,脑子有点乱。我懂JS里if/else的基础,但不知道怎么写个循环——当第一个问题输入No时,强制用户回到问题1?

我的代码目前是这样的:

# initial input
question1 = input("Would you like to check the next UK Bank Holiday? [Yes/No?] ")
#next input
if question1.lower() == 'yes':
    print('Let\'s get started')
#if input is no 
elif question1.lower() == 'no':
    print('That is all the code does, please answer yes or no')
## do i need to create the input again here?

请问是否需要在此处重新创建输入?


不需要重复编写输入代码,用while循环就能优雅解决这个问题。把输入和判断逻辑放进循环体,直到用户输入Yes才终止循环即可。

修改后的完整代码:

while True:
    question1 = input("Would you like to check the next UK Bank Holiday? [Yes/No?] ")
    if question1.lower() == 'yes':
        print("Let's get started")
        break  # 输入Yes时跳出循环,执行后续逻辑
    elif question1.lower() == 'no':
        print("That is all the code does, please answer yes or no")
    else:
        print("请输入Yes或No")  # 处理非预期输入,提升用户体验

关键逻辑说明:

  • while True 构建一个无限循环,只有遇到break语句才会停止
  • 每次循环都会重新获取用户输入,无需重复编写input()语句
  • 输入Yes时,打印提示后通过break退出循环,程序可继续执行后续的银行假日查询代码
  • 输入No时,打印提示后循环自动回到开头,重新询问问题
  • 新增的else分支用于处理用户输入其他内容的情况,避免程序无响应

内容的提问来源于stack exchange,提问作者Natalie McGreevy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 22:44:57