当程序重复时,它会打印出相同的数字。我尝试编辑它,但即使它打印出不同的数字,它也只接受第一个问题的答案。这是我的代码:
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}")
不知道哪一部分出了问题或如何解决。
问题是
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}")