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

Python循环无法中断求助:旅行助手程序主菜单循环问题

问题解决:主菜单循环无法中断

你的循环无法终止的关键问题是字符串方法调用错误:
在获取用户确认输入的代码行中,你使用了.upper而不是.upper(),这导致check变量存储的是字符串的upper方法对象,而非转换后的大写字符串,因此永远无法匹配到'YES'或'NO',循环也就一直无法中断。

修改后的核心代码片段:

##Opening info##
##V3.1##
enter = 'GO'  # 无需global声明,当前作用域可直接使用
while enter == 'GO':
    print("========================================================================================================================================================================================")
    print("")
    print("Welcome to the Traveller Assisstant. This program is able to help you with currency conversions, date and time conversions and viewing weather details of your destination.")
    print("")
    print("========================================================================================================================================================================================")
    time.sleep(2.5)
    ori = str(input("Please enter your current country: "))
    dest = str(input("Please enter your destination country: "))
    time.sleep(5)
    # 修复:调用upper()方法将输入转为大写
    check = str(input(f"Are you sure you are in {ori}, and would like to go to {dest}? ")).upper()
           
    if check == 'YES':
        enter = 'STOP'
    elif check == 'NO':
        print("Returning to Location Selector")
        enter = 'GO'

额外优化建议:

  • 移除不必要的global enter声明,变量enter在当前作用域内定义,无需全局声明。
  • 使用f-string格式化确认提示语,代码更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:15:29