我正在编写一个测试算术技能的程序。 它应该生成随机问题,并给出随机操作。 这是我的代码:
import random
score = 0
counter = 0
ops = ['+', '-', '*', '/']
def question():
num1 = random.randint(0,10)
num2 = random.randint(1,10) #Starts from 1 to avoid zerodivision error
operation = random.choice(ops)
question = float(input(f"What is {num1} {operation} {num2}?: "))
global answer
answer = eval(str(num1) + operation + str(num2))
global counter
counter = counter + 1
def points():
while counter < 10:
question()
if question == answer:
print("\nCorrect!\n")
global score
score = score + 1
else:
print(f"\nWrong! The answer is {answer}\n")
points()
print(f"\nYou got {score} out of {counter}")
但它给出了这个输出:
What is 9 + 3?: 12
Wrong! The answer is 12
如果输入与答案匹配,则应该说正确,并计算分数,最后打印出满分 10 分的分数。
请帮我解决这个问题。
最佳答案
问题出在
if question == answer:
在那一行中,question
是对您之前定义的function question()
的引用。由于 answer
是一些保存问题答案的 int
,因此 ==
始终为 False
。您永远无法真正了解用户输入的内容。
要解决这个问题,请执行以下操作:
def question():
num1 = random.randint(0,10)
num2 = random.randint(1,10) #Starts from 1 to avoid zerodivision error
operation = random.choice(ops)
user_answer = float(input(f"What is {num1} {operation} {num2}?: "))
global answer
answer = eval(str(num1) + operation + str(num2))
global counter
counter = counter + 1
return user_answer
def points():
while counter < 10:
user_answer = question()
if user_answer == answer:
print("\nCorrect!\n")
global score
score = score + 1
else:
print(f"\nWrong! The answer is {answer}\n")
我更改了名称,以便更清楚地说明发生了什么。
作为附录,我强烈建议不要使用全局变量。它们几乎从不需要并且通常会混淆问题。例如,我认为
def question():
num1 = random.randint(0,10)
num2 = random.randint(1,10) #Starts from 1 to avoid zerodivision error
operation = random.choice(ops)
user_answer = float(input(f"What is {num1} {operation} {num2}?: "))
real_answer = eval(str(num1) + operation + str(num2))
return user_answer, real_answer
def points():
score = 0
for questions_asked in range(1, 11):
user_answer, real_answer = question()
if user_answer == real_answer:
print("\nCorrect!\n")
score += 1
else:
print(f"\nWrong! The answer is {answer}\n")
这使得程序流程更容易理解。
关于python - 程序给出了意外的输出——为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47255252/