随机陈述问同样的陈述?蟒蛇

时间:2015-02-25 15:00:27

标签: python loops random range

我一直试图进行一个数学测验,询问一个随机问题,然后再问一个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!!")

3 个答案:

答案 0 :(得分:1)

列出以下几行:

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循环中移动这些语句,以便每次需要新值时重新评估它们

答案 1 :(得分:1)

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

...

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()
    ...

答案 2 :(得分:1)

您没有更新num1,num2,ops,问题和答案变量。您需要将它们移动到for循环中。否则它们将始终等于它们被分配的第一个值。