Python中if-elif逻辑异常:Child-Pugh评分代码返回固定值问题
问题排查与修复方案
核心问题分析
- 累加语法错误:所有
total =+n是赋值为+n,而非累加,正确写法是total +=n——这是total始终为1的根本原因。 - 条件判断逻辑错误:
encephalopathie和ascite是单个字符串,却和列表做相等比较(比如encephalopathie == ["Absente"]),导致这部分分数从未被累加。 - 类型不匹配:
answer_int = input(...)后仅执行int(answer_int)但未赋值,导致answer_int仍是字符串,无法与整数total比较。child被赋值为列表(如["A"]),而用户输入的answer_child是字符串,两者永远不相等。
- 分支覆盖不全:如果
total不在5-10的范围内,child会保持初始的空列表[]。 - 大小写不一致:最后一个分支赋值
child = ["c"]应为大写"C",与用户输入选项匹配。
修正后的代码
from random import * x = ["Absente", "Stade 1", "Stade 2", "Stade 3", "Stade 4"] y = ["Absente", "Discrète", "Abondante"] encephalopathie = choice(x) ascite = choice(y) bilirubine = randint(15,70) albumine = randint(15, 45) TP = randint(5, 80) total = 0 # 修正累加语法为 += if TP > 50 : total +=1 elif 40 <= TP <= 50 : total +=2 elif TP < 40 : total +=3 if albumine > 35 : total +=1 elif 28 <= albumine <= 35 : total +=2 elif albumine < 28 : total +=3 if bilirubine < 35 : total +=1 elif 35 <= bilirubine <= 50 : total +=2 elif bilirubine > 50 : total +=3 # 修正条件判断:单个字符串与列表成员比较 if encephalopathie == "Absente" : total +=1 elif encephalopathie in ["Stade 1", "Stade 2"] : total +=2 elif encephalopathie in ["Stade 3", "Stade 4"]: total +=3 if ascite == "Absente" : total +=1 elif ascite == "Discrète" : total +=2 elif ascite == "Abondante": total +=3 # 改为字符串赋值,覆盖所有总分范围 if 5<= total <= 6 : child = "A" elif 7 <= total <= 9 : child = "B" elif total >= 10 : child = "C" else: child = "无效分数" # 处理异常总分情况 print('Tp =', TP, "Bilirubine =", bilirubine, "Albumine =", albumine, "Ascite =", ascite, "Encephalopathie =", encephalopathie) answer_int = input("Quel est la cotation du score en chiffre ?") answer_int = int(answer_int) # 转换后赋值给变量 answer_child = input("Quel est le score de Child-Pugh ? A, B ou C ?") # 修正比较逻辑,兼容用户小写输入 if answer_child.upper() == child and answer_int == total : print("Vrai") else : print(f"Faux, la bonne réponse est Child {child}, {total}")
额外优化
- 增加
answer_child.upper(),兼容用户输入小写字母的情况。 - 增加
else分支处理异常总分,避免child为空。 - 调整输出格式为f-string,提升可读性。
内容的提问来源于stack exchange,提问作者Serfrousse Serfrousse
相关产品推荐
相关产品推荐

