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

Python算术练习程序break/continue报错,如何根据用户输入重启程序?

算术练习程序问题修复方案

核心问题说明

你的代码存在三个导致报错和功能异常的问题:

  • 循环控制语句位置错误:break和continue只能在循环体内部使用,你当前把重试判断逻辑放在了while True的缩进范围外,运行会直接触发语法错误。
  • 随机数生成位置错误:a、b的随机生成逻辑放在了循环外,就算循环能正常运行,每次生成的题目都是完全相同的,不会更新新的数值。
  • 变量未定义风险:a < b、a == b的分支内没有单独获取用户输入的answer变量,若运行时优先触发这两个分支,会直接报变量未定义错误。

修复后可运行代码

import random

goodQuotes = ["Nice job", "Keep going", "Excellent", "Great job", "You are doing great"]
badQuotes = ["You got that wrong", "Unfortunately that is incorrect", "Try again", "Retry this problem", "You made a mistake"]

while True:
    # 每次循环生成新的随机题目
    a = random.randint(0, 1000)
    b = random.randint(0, 1000)
    
    if a > b:
        print(f'What is {a} - {b}')
        answer = int(input("Enter your answer: "))
        if answer == a - b:
            print(random.choice(goodQuotes))
        else:
            print(random.choice(badQuotes))
    elif a < b:
        print(f'What is {a} + {b}')
        answer = int(input("Enter your answer: "))
        if answer == a + b:
            print(random.choice(goodQuotes))
        else:
            print(random.choice(badQuotes))
    else:
        print(f'What is {a} * {b}')
        answer = int(input("Enter your answer: "))
        if answer == a * b:
            print(random.choice(goodQuotes))
        else:
            print(random.choice(badQuotes))
    
    # 重试逻辑放在循环内部
    retry = input("Want to try another problem, enter yes or no: ").strip().lower()
    if 'yes' in retry:
        continue
    elif 'no' in retry:
        print("Good Bye")
        break
    else:
        print("Invalid Input, exit program.")
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:45:03