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

我的if语句或dictionary(字典)存在问题吗?输入成绩后总触发else分支

问题原因
  • 你定义的grade字典键为大写字母(A/C/E/F),但代码中对用户输入调用了.lower()方法,会将所有输入内容转为小写,比如输入A会被处理为a,大小写不匹配自然无法命中字典键。
  • Python中字典的in判断是区分大小写的,'a'和'A'会被判定为两个完全不同的值,因此你的判断逻辑永远不会触发if分支。
修复方案

有两种可选修改方式:

  1. 将grade字典的键改为小写,适配你转小写的输入逻辑:
courses = {"Biology": 100, "English": 100, "Math": 100}
# 字典键改为小写
grade = {"a": 20, "c": 15, "e": 10, "f": 0}

print("Type your grade A,C,E or F")
for i in courses:
    question = input("What grade do you have in " + i + ":").lower()
    if question in grade:
        print("check")
    else:
        print("nocheck")
  1. 将输入处理方法改为.upper(),适配原字典的大写键:
courses = {"Biology": 100, "English": 100, "Math": 100}
grade = {"A": 20, "C": 15, "E": 10, "F": 0}

print("Type your grade A,C,E or F")
for i in courses:
    # 把lower改为upper,将输入转为大写
    question = input("What grade do you have in " + i + ":").upper()
    if question in grade:
        print("check")
    else:
        print("nocheck")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:45:03