编写Python while循环后无法正常跳出,请求排查问题原因
问题原因分析
你的代码存在两个核心逻辑错误,导致无法达到预期效果:
- break位置错误:当输入有效的数字选项(1-4)时,代码会立即执行
break跳出循环,此时后面处理选项的逻辑(调用对应函数、退出程序)根本没有机会运行。 - 类型不匹配:将输入的字符串转为int后,后续判断
choice == "1"是用整数和字符串比较,永远不会成立,即使没有break,也无法触发对应的操作。
修复后的代码
import re def display_menu(gbook): print("") print("Please choose an option below:") print("") print("1. Record a grade") print("2. Print all grades") print("3. Calculate GPA") print("4. Exit") print("_________________________________________") while True: print("") choice = input("Please select a numbered option from above: ") if re.match(r'^\d+$', choice): choice = int(choice) if choice == 1: record_grade(gbook) elif choice == 2: print_grades(gbook) elif choice == 3: calculate_gpa(gbook) elif choice == 4: exit() else: print("Invalid choice. Please try again.") else: print("Invalid choice. Please try again.")
逻辑说明
- 输入验证通过后,直接将int类型的choice与数字选项匹配,执行对应操作
- 选择4时直接退出程序,其他选项执行完功能后会回到循环开头,重新显示菜单(如果需要执行完操作后退出循环,可在对应分支添加
break) - 无效输入(非数字或不在1-4范围内)会提示错误并重新进入输入流程
内容的提问来源于stack exchange,提问作者Benjamin Frame
相关产品推荐
相关产品推荐

