Python代码中if语句恒返回True的问题排查与修复求助
问题排查:人气值兼容判断始终返回True的原因
核心问题:数值维度不匹配
你的代码里存在自己的人气值与好友人气值计算维度不一致的关键错误:
- 计算自身
poplr时,直接返回了popularity()的原始结果(未乘以10) - 计算好友
friend_poplr时,却额外乘以了10
这导致判断基准完全错位:
比如你的实际人气值对应打印的65%(即poplr*10=65),但代码中用未缩放的6.5作为判断基准,计算出的范围是6.5-10=-3.5到6.5+10=16.5。而好友的人气值是乘以10后的正数,必然满足friend_poplr > -3.5,如果好友的人气值小于16.5就会被误判为兼容,哪怕实际差值远超10。
修复步骤
统一数值维度:将自身人气值也乘以10,和好友的计算逻辑对齐
poplr = popularity(gfactor, social, smartness, sports) * 10对应的打印代码可以简化为:
print(str(math.ceil(poplr)) + "%")简化判断逻辑:用绝对值判断差值是否在10以内,替代嵌套if,代码更清晰
if abs(friend_poplr - poplr) <= 10: print(f"# {i} is a compatible friend #") else: print(f"# {i} is not a compatible friend #")修复文件读取隐患:固定读取37字节可能导致JSON不完整引发解析错误,建议读取整个文件内容;同时用
with语句自动管理文件资源with open(f"{i}.txt") as fs: json_str = fs.read() data = json.loads(json_str)
修复后的完整代码示例
import math import json def popularity(G, So, Sm, Sp): g = float(G) * 0.3 so = float(So) * 0.4 sm = float(Sm) * 0.1 sp = float(Sp) * 0.2 return g + so + sm + sp gfactor = input("What is your G-Factor? ") social = input("What is your Social Quotient? ") smartness = input("What is your smartness level? ") sports = input("What is your sports skill? ") poplr = popularity(gfactor, social, smartness, sports) * 10 print(str(math.ceil(poplr)) + "%") print("Finding friends... ") for i in friends: with open(f"{i}.txt") as fs: json_str = fs.read() data = json.loads(json_str) friend_poplr = popularity(data["g"], data["So"], data["Sm"], data["Sp"]) * 10 if abs(friend_poplr - poplr) <= 10: print(f"# {i} is a compatible friend #") else: print(f"# {i} is not a compatible friend #")
内容的提问来源于stack exchange,提问作者Dark Shadow
相关产品推荐
相关产品推荐

