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

Python初学者求助:如何避免数学题生成程序重复同一算式?

解决数学题程序重复题目问题

你的代码之所以每次输出同一道题,核心原因是生成随机数和运算符的代码放在了for循环外面——num1、num2、operator只会在程序一开始生成一次,整个循环过程中都复用这组值,自然题目不会变。

把这些变量的生成逻辑移到for循环内部,就能每次生成新的题目了,同时还可以优化一些细节避免其他问题,修改后的代码如下:

import random

num_question = int(input("Enter how many questions would you like to solve: "))
oper = ["+", "-", "*", "/"]

for count in range(num_question):
    # 每轮循环都重新生成随机数和运算符
    num1 = random.randint(0, 20)
    num2 = random.randint(0, 20)
    operator = random.choice(oper)
    
    # 更友好的题目展示格式
    print(f"What is {num1} {operator} {num2}?")
    
    # 处理输入,允许整数或浮点数
    try:
        guess = float(input("Enter here: "))
    except ValueError:
        print("请输入有效的数字!")
        continue
    
    answer = 0
    if operator == "+":
        answer = num1 + num2
    elif operator == "-":
        answer = num1 - num2
    elif operator == "*":
        answer = num1 * num2
    elif operator == "/":
        # 避免除以零的错误
        if num2 == 0:
            print("除数不能为零,重新生成题目...")
            continue
        answer = num1 / num2
    
    # 浮点数精度兼容,不用严格相等
    if abs(guess - answer) < 0.001:
        print("Correct!")
    else:
        print(f"Incorrect. The right answer is {answer}.")

关键修改说明:

  • 将num1、num2、operator的生成代码移入for循环,确保每道题都是新的随机组合。
  • 用f-string格式化题目输出,替代原来的元组打印,让题目更直观。
  • 针对除法场景做了两处优化:避免除以零导致程序崩溃,以及用浮点数接收输入并通过精度范围判断答案(解决整数输入和浮点答案不匹配的问题)。
  • 增加了输入异常处理,防止用户输入非数字导致程序报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:18:26