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

Python数学游戏代码问题:无法生成新随机数,重复输出相同数字

解决数学游戏随机数不更新的问题

问题原因

你的代码中num1和num2仅在程序启动时生成一次,while循环内没有更新这两个变量的逻辑,因此无论答对答错,都会重复显示同一道题。

解决方案

要实现答对题目后生成新随机数的需求,只需在答对的分支中重新生成num1和num2即可。以下是修改后的完整代码:

import random

print("Enter A for addition:")
print("Enter B for subtraction:")
print("Enter C for multiplication:")
print("Enter D for division:")
print("Enter E for exit:")
options = str(input("Hello,Please enter an option:"))

# 初始化第一组随机数
num1 = random.randrange(1, 21)
num2 = random.randrange(1, 21)

if options == 'E':
    print("Enter E(In caplocks to quit):")
    exit()

while options == 'A':
    real1 = num1 + num2
    print("What is", num1, "+", num2, ":")
    # 修正输入提示的语法错误
    answer_question = int(input("Hello,Please enter the answer to the question:"))
    if answer_question == real1:
        print("You are correct!")
        # 答对后生成新的随机数
        num1 = random.randrange(1, 21)
        num2 = random.randrange(1, 21)
    else:
        print("You are incorrect!!!!")

额外优化(可选)

如果希望无论答对答错都切换新题目,可以将随机数生成逻辑移到while循环的开头,这样每次循环都会生成新的运算数:

import random

print("Enter A for addition:")
print("Enter B for subtraction:")
print("Enter C for multiplication:")
print("Enter D for division:")
print("Enter E for exit:")
options = str(input("Hello,Please enter an option:"))

if options == 'E':
    print("Enter E(In caplocks to quit):")
    exit()

while options == 'A':
    # 每次循环生成新的随机数
    num1 = random.randrange(1, 21)
    num2 = random.randrange(1, 21)
    real1 = num1 + num2
    print("What is", num1, "+", num2, ":")
    answer_question = int(input("Hello,Please enter the answer to the question:"))
    if answer_question == real1:
        print("You are correct!")
    else:
        print("You are incorrect!!!!")

内容的提问来源于stack exchange,提问作者Solo Leveling

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:05:25