You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm与Spyder IDE运行Python测验代码输出异常求助

Python测验代码在IDE中判错问题排查与解决

问题描述

编写的Python测验代码在ProgramBiz在线解释器中运行正常,但在PyCharm和Spyder IDE中,输入正确答案却被判定为错误。代码如下:

quiz = {
    "question1": {
       "question": "What is the capital of France?",
       "answer": "Paris"
    },
    "question2": {
        "question": "What is the capital of Germany?",
        "answer": "Berlin"
    },
    "question3": {
        "question": "What is the capital of Italy?",
        "answer": "Rome"
    },
    "question4": {
        "question": "What is the capital of Spain?",
        "answer": "Madrid"
    },
    "question5": {
        "question": "What is the capital of Portugal?",
        "answer": "Lisbon"
    },
    "question6": {
        "question": "What is the capital of Switzerland?",
        "answer": "Bern"
    },
    "question7": {
        "question": "What is the capital of Austria?",
        "answer": "Vienna"
    }
}

score = 0

for key, value in quiz.items():
    print(value['question'])
    answer = input('Answer ?')

    if answer.lower() == value['answer'].lower():
        print('Correct')
        score = score + 1
        print('Your score is: ' + str(score))
        print(' ')
        print(' ')

    else:
        print('Wrong!')
        print('The answer is :' + value['answer'])
        print('Your score is:' + str(score))
        print(' ')
        print(' ')

print('You got ' + str(score) + 'out of 7 questions correctly!')
print('Your percentage is ' + str(score/7 * 100) + '%')

问题原因

PyCharm、Spyder这类IDE的输入组件不会自动去除用户输入内容的首尾空白字符(比如空格、换行符、制表符)。如果输入时不小心多打了空格,或者粘贴的内容带有空白,就会导致输入字符串与正确答案的字符串不匹配,从而被判定错误。而部分在线解释器会自动清理输入的首尾空白,因此在线环境下运行正常。

解决方案

在获取用户输入后,调用strip()方法去除首尾空白字符,再进行大小写统一后的比较。修改后的关键代码如下:

for key, value in quiz.items():
    print(value['question'])
    answer = input('Answer ?').strip()  # 新增strip()处理输入

    if answer.lower() == value['answer'].lower():
        # 后续逻辑保持不变
        print('Correct')
        score = score + 1
        print('Your score is: ' + str(score))
        print(' ')
        print(' ')

    else:
        print('Wrong!')
        print('The answer is :' + value['answer'])
        print('Your score is:' + str(score))
        print(' ')
        print(' ')

也可以选择在比较时直接对输入和答案做空白清理,效果一致:

if answer.strip().lower() == value['answer'].strip().lower():

这样就能避免因输入的首尾空白导致的匹配错误,在IDE和在线环境中都能正常运行。

内容的提问来源于stack exchange,提问作者Kafka2701

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 09:44:53