You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

求助:Python测验答题函数输入正确答案仍返回错误问题

问题解决:测验题函数总是返回"wrong"的原因及修复方案

嘿,我一眼就瞅出问题所在啦!你写的函数里有个很容易踩的小坑:

input()函数获取的用户输入默认是字符串类型,而你传入的答案26是整数类型。哪怕用户输入的是26,它实际是字符串'26',和整数26直接做相等比较,结果肯定是不相等的,所以程序才会一直输出wrong

下面给你两种简单的修复方案:

方案一:把用户输入转换成整数

直接用int()函数把输入的字符串转成整数,这样就能和整数类型的答案正常比较了:

def bst_q(question, answer):
    rq = int(input(str(question)))  # 将输入转为整数
    if rq == answer:
        print('Correct, Well done')
    else:
        print('wrong')

bst_q('What is 13 times 2?', 26 )

方案二:把答案转换成字符串

反过来,把整数类型的答案转成字符串,和输入的字符串做比较:

def bst_q(question, answer):
    rq = input(str(question))
    if rq == str(answer):  # 将答案转为字符串
        print('Correct, Well done')
    else:
        print('wrong')

bst_q('What is 13 times 2?', 26 )

额外优化:处理非数字输入(可选)

如果担心用户输入非数字内容导致程序报错,可以加个异常处理,让函数更健壮:

def bst_q(question, answer):
    try:
        rq = int(input(str(question)))
        if rq == answer:
            print('Correct, Well done')
        else:
            print('wrong')
    except ValueError:
        print('Please enter a valid number!')

bst_q('What is 13 times 2?', 26 )

内容的提问来源于stack exchange,提问作者A.Salihu

火山引擎 最新活动