随机陈述询问相同的陈述? Python

Random statement asking same statement?? Python

我一直在尝试做一个数学测验,先问一个随机问题,然后问另一个随机问题 10 次,我的问题是它会问一个随机问题,然后一遍又一遍地问同样的问题等等

import random

opList = ["+", "*", "-"]
numberofQuestions = 10
num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
ops = random.choice(opList)
question = "%d %s %d" % (num1, ops, num2)
answer = eval(question)
totalScore = 0


childName = input("Enter your name: ")
print("Thank you for signing up for Arithmetic Quiz " + childName)
for i in range(numberofQuestions):
    reply = int(input("What is " + question + " ? "))
    if reply == answer:
        print("Correct!!")
        totalScore += 1
    else:
        print("Incorrect!!")

放置这些行:

num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
ops = random.choice(opList)
question = "%d %s %d" % (num1, ops, num2)
answer = eval(question)

你有的地方意味着他们只评估一次,为每个变量分配随机选择但静态的值。

您需要将这些语句移动到您的 for 循环中,以便在您每次需要新值时重新计算它们

问题是您只生成一次问题(和问题的组成部分)。我的建议是像这样生成一个新函数:

...

def question_answer():
    num1 = random.randint(0, 10)
    num2 = random.randint(0, 10)
    ops = random.choice(opList)
    question = "%d %s %d" % (num1, ops, num2)
    answer = eval(question)
    return question, answer

for i in range(numberofQuestions):
    question, answer = question_answer()
    ...

您没有更新 num1、num2、ops、question 和 answer 变量。您需要将它们移动到 for 循环中。否则它们将始终等于分配给它们的第一个值。