程序重复相同的问题,而不是生成一组新的数字和运算符

问题描述 投票:0回答:1

当程序重复时,它会打印出相同的数字。我尝试编辑它,但即使它打印出不同的数字,它也只接受第一个问题的答案。这是我的代码:

import random
count=0
correct = 0
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
operator = random.choice(['+', '-', '*', '/'])
name = str(input(f"what is your name?"))
question = int(input(f"what is the answer to: {num1} {operator} {num2}"))
if operator == '+':
    answer = num1 + num2
elif operator == '-':
    answer = num1 - num2
elif operator == '/':
    answer = num1 / num2
else:
    answer = num1 * num2
while count < 2:
    if question == answer:
        count=count+1
        correct=correct+1
        print(f"well done {name}, you're correct")
        question = int(input(f"what is the answer to: {num1} {operator} {num2}"))
    else:
        print(f"the answer was {answer}")
        count = count+1
        correct=correct
        question = int(input(f"what is the answer to: {num1} {operator} {num2}"))
else:
    print(f"your score is {correct}, you got this this many correct, well done {name}")

不知道哪一部分出了问题或如何解决。

python random
1个回答
0
投票

问题是

num1
num2
operator
的随机生成发生在 while 循环之外。如果将它们放入循环中,每次迭代都会再次生成这些值:

import random

count = 0
correct = 0

name = str(input(f"what is your name?\n"))

while count < 2:
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    operator = random.choice(["+", "-", "*", "/"])
    question = int(input(f"what is the answer to: {num1} {operator} {num2}?\n"))
    if operator == "+":
        answer = num1 + num2
    elif operator == "-":
        answer = num1 - num2
    elif operator == "/":
        answer = num1 / num2
    else:
        answer = num1 * num2
    if question == answer:
        count = count + 1
        correct = correct + 1
        print(f"well done {name}, you're correct")
    else:
        print(f"the answer was {answer}")
        count = count + 1
else:
    print(f"your score is {correct}, you got this this many correct, well done {name}")
© www.soinside.com 2019 - 2024. All rights reserved.