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
相关产品推荐
相关产品推荐

