Python 权重转换器程序-平凡问题

Python 权重转换器程序-平凡问题,python,python-3.x,Python,Python 3.x,我从零开始学习python,我有一个非常琐碎的问题。 我想写这个程序,在其中输入我的体重和单位(磅或千克),然后得到转换: weight = int(input("Weight: ")) unit = input("Lbs or Kg") if unit.upper() == "L" or "l": print(f"You are {weight / 2.2} kilos") elif u

我从零开始学习python,我有一个非常琐碎的问题。 我想写这个程序,在其中输入我的体重和单位(磅或千克),然后得到转换:

weight = int(input("Weight: "))
unit = input("Lbs or Kg")
if unit.upper() == "L" or "l":
    print(f"You are {weight / 2.2} kilos")
elif unit.upper() == "K":
    print(f"You are {weight * 2.2} pounds")
else:
    print("Unknown unit")
当我选择“L”作为单位时,一切都很好,但当我输入“K”时,程序将除法而不是乘法(就像我输入“L”),我不明白为什么。我的代码出了什么问题? 谢谢您的帮助。

需要删除“l”,因为它将刚刚返回

你可以通过跑步看到这一点

unit = "k"
unit.upper() == "L" or "l"
输出

'l'
如果在Python中返回某个内容,它将被计算为“True”(不包括“None”或“0”等异常)

从代码中删除“或“l”部分。if语句当前的计算结果为(unit.upper()==“L”)或(“L”),而“L”的计算结果为true,因此永远不会到达elif

weight = int(input("Weight: "))
unit = input("Lbs or Kg")
if unit.upper() == "L":
    print(f"You are {weight / 2.2} kilos")
elif unit.upper() == "K":
    print(f"You are {weight * 2.2} pounds")
else:
    print("Unknown unit")

您使用的if语句是错误的。如果您想比较2个字符,您应该这样做:

weight = int(input("Weight: "))
unit = input("Lbs or Kg: ")
if unit == 'L' or unit == 'l':
    print(f"You are {weight / 2.2} kilos")
elif unit == 'K' or unit == 'k':
    print(f"You are {weight * 2.2} pounds")
else:
    print("Unknown unit")
但由于使用了.upper()方法,因此只需从if语句中删除“l”,即可得到以下结果:

weight = int(input("Weight: "))
unit = input("Lbs or Kg: ")
if unit.upper() == 'L':
    print(f"You are {weight / 2.2} kilos")
elif unit.upper() == 'K':
    print(f"You are {weight * 2.2} pounds")
else:
    print("Unknown unit")

始终确保检查“if”中的所有条件。

需要从
if中删除“l”remove
或“l”
。请参阅,在本例中,它不能是
“l”
,因为您已转换为大写。但更一般地说,这不是测试表达式是否具有多个值中的一个值的方法。例如,您可以在(“L”、“LB”)中使用
if unit.upper():
。这是否回答了您的问题?完整规则: