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

编写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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:18:31