程序给出意想不到的输出 - 为什

时间:2017-11-12 23:40:26

标签: 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

如果输入与答案匹配,则应该说正确,并计算得分,并在结尾打印十分。

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:3)

问题在于

if question == answer:

在该行中,question是对您之前定义的函数 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")

这使得理解程序流程变得更加容易。

答案 1 :(得分:1)

Josh Karpel已经回答了你的问题,但我只是想我指出另一个问题。

分区总是会产生float而不是int,因此如果用户说4 / 22 ...脚本会说答案是错误的,因为它正在对"2""2.0"进行细致的比较。这就是为什么在Josh的版本中,他将用户答案转换为float。这样就可以用数字比较答案。

此外,该脚本目前能够询问What is 4 / 7 ?这样的人难以回答的问题。一种解决方法是将num2随机化,直到它被num1整除。

def question():
    num1 = random.randint(0, 10)
    num2 = random.randint(1, 10)
    operation = random.choice(ops)
    if operation == '/':
        while num1 % num2 != 0:
            num2 = random.randint(1, 10)
    # do eval