首页 > 解决方案 > Python初学者:if语句不返回打印函数

问题描述

我最近尝试用这段代码做一个爱情计算器。但是,当面对一个包含超过 11 个字符的“love”或“true”共同字符的名称时,它不会返回正确的语句。例如,如果我因为“love”语句超过 9 而返回 711,它只会给我“else”选项而不是 => 90 语句。我不确定我做错了什么。感谢您提前提供任何帮助!

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())

t = combined_names.count('t')
r = combined_names.count('r')
u = combined_names.count('u')
e = combined_names.count('e')

l = combined_names.count('l')
o = combined_names.count('o')
v = combined_names.count('v')
e = combined_names.count('e')

Love = l + o + v + e
true = t + r + u + e
truelove = int(str(true) + str(Love))

if truelove <= 10 and truelove >= 90:
  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}")

标签: python

解决方案


truelove <= 10 and truelove >= 90

将始终给出false并且不通过此 if 语句。
为了能够运行它,您可以尝试。

truelove >= 10 and truelove <= 90

编辑:我看到你的elif陈述永远不会奏效,因为第一个if陈述范围更广。所以翻转 if 语句将解决它。

if truelove >= 40 and truelove <= 50:
  print(f"Your score is {truelove}, you are alright together")
elif truelove >= 10 and truelove >= 90:
  print(f"Your score is {truelove}, you go together like coke and mentos")
else:
  print(f"Your score is {truelove}")```

推荐阅读