我的if语句或dictionary(字典)存在问题吗?输入成绩后总触发else分支
问题原因
- 你定义的
grade字典键为大写字母(A/C/E/F),但代码中对用户输入调用了.lower()方法,会将所有输入内容转为小写,比如输入A会被处理为a,大小写不匹配自然无法命中字典键。 - Python中字典的
in判断是区分大小写的,'a'和'A'会被判定为两个完全不同的值,因此你的判断逻辑永远不会触发if分支。
修复方案
有两种可选修改方式:
- 将
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")
- 将输入处理方法改为
.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
相关产品推荐
相关产品推荐

