返回“不正确”不管

2024-10-02 18:14:19 发布

您现在位置:Python中文网/ 问答频道 /正文

这已经被标记为一个重复,我当时不知道这个问题,但我将采取这个职位在未来48小时下来,道歉。你知道吗

我目前正在开发一个python(v3.5.0:374f501f4567)程序,该程序使用乘法、加法或减法生成ranom方程。代码一直工作到最后一关。当我试图回答正确或不正确时,我完全被难住了。当我使用以下代码时:

import random
from operator import add,sub,mul
x=random.randint(0,10)
y=random.randint(0,10)
eqn=(add, sub, mul)
eqnchoice=random.choice(eqn)
eqnstring={add:'+',sub:'-',mul:'*'}
useranswer=0
def eqngenerator():
    random.seed
    answer=eqnchoice(x,y)
    answer=round(answer,2)
    print("what's the answer to",x,eqnstring[eqnchoice],y,"=?\n")
    useranswer=input("Enter the answer here:")
    if useranswer==answer:
        print('Correct!')
    else:
        print('Incorrect!')

print(eqngenerator())

下面的截图显示了我面临的问题。你知道吗

the first image is an incorrect answer returning 'incorrect!'

The second image is a correct answer but, it is also returning 'incorrect!'

我不明白为什么会这样,如果有人能帮忙的话,请帮忙。 谢谢你抽出时间。你知道吗


Tags: the代码answerimport程序addrandomprint
2条回答

input返回一个字符串,因此需要:

useranswer=float(input("Enter the answer here:"))

如果用户输入任何其他值,然后输入数字,则会引发错误,因此您可以:

def eqngenerator():
    random.seed
    answer=eqnchoice(x,y)
    answer=round(answer,2)
    print("what's the answer to",x,eqnstring[eqnchoice],y,"=?\n")
    useranswer=input("Enter the answer here:")
    try:
        if useranswer==answer:
            print('Correct!')
        else:
            print('Incorrect!')
    except ValueError:
        print('Incorrect!')

input()将在useranswer变量中提供一个字符串。它在使用前需要转换成一个数字,如浮点数或整数

useranswer = int(input("Enter the answer here:"))
or
useranswer = float(input("Enter the answer here:"))

如果您知道计算的答案总是整数,请使用int

相关问题 更多 >