python - 程序给出了意外的输出——为什么?

标签 python python-3.x

我正在编写一个测试算术技能的程序。 它应该生成随机问题,并给出随机操作。 这是我的代码:

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/

相关文章:

python - 在Python中,如何根据扩展名从文本文件中提取文件名并将其放入新的文本文件中?

python - 错误 : ' No module named ' django. core.urlresolvers'

Python 库,用于制作带有选项等的漂亮命令行脚本

python - Cython编译错误

python - 如何从 https ://stackoverflow. com/?tab=month 中提取元素(标题名称、投票、 View 、每个标题的答案)?

Python 在 OS X 上的文本文件中捕获击键值

python - 多线程和 SQLalchemy

python - 如何并行运行生成器代码?

python - 在 Python 3 中将字符添加到字符串的多个位置

python-3.x - 需要帮助找到 2 个单独的轮廓而不是 MICR 代码中的组合轮廓