You need to enable JavaScript to run this app. Python新手开发爱情计算器时if语句未触发预期print分支问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Python新手开发爱情计算器时if语句未触发预期print分支问题求助

代码问题排查与修正

核心逻辑错误

  • 第一判断分支的条件存在致命矛盾:原代码写为truelove <= 10 and truelove >= 90,该条件在数学上永远无法成立——不存在同时满足「小于等于10」和「大于等于90」的整数,因此无论truelove计算出什么值,这个分支都不会被触发,程序会直接跳过对应逻辑,最终走入else的默认输出,这是你遇到运行异常的根本原因。
  • 存在冗余重复代码:计算Love变量时重复为e变量赋值,虽然两次取的字符计数结果一致,不影响最终数值,但属于无意义的重复编写。
  • 分数拼接的边界适配缺失:当某一维度的字符统计数达到两位数时(如你提到的love维度统计为11),字符串拼接生成的truelove会成为三位数(你例子中的711),如果判断规则仍按两位得分的范围设置,这类超范围的数值会直接无法匹配对应分支。

修正后可直接运行的代码

print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")

combined_names = str(name1.lower()) + str(name2.lower())

# 统计true维度对应字符总数
t = combined_names.count('t')
r = combined_names.count('r')
u = combined_names.count('u')
e = combined_names.count('e')
true = t + r + u + e

# 统计love维度对应字符总数(移除重复的e赋值)
l = combined_names.count('l')
o = combined_names.count('o')
v = combined_names.count('v')
Love = l + o + v + e

# 拼接生成最终匹配得分
truelove = int(str(true) + str(Love))

# 修正判断逻辑:符合分数区间时触发对应输出
if truelove >= 90 or truelove <= 10:
  print(f"Your score is {truelove}, you go together like coke and mentos")
elif truelove >= 40 and truelove <= 50:
  print(f"Your score is {truelove}, you are alright together")
else:
  print(f"Your score is {truelove}")

效果说明

修正后,当计算得到truelove=711这类远高于90的数值时,会直接匹配第一个判断分支输出对应文案,不会直接走入else逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 17:15:01