这种情况下会发生什么?python基础知识[duplicate]

toe95027  于 2023-01-19  发布在  Python
关注(0)|答案(1)|浏览(156)
    • 此问题在此处已有答案**:

Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?(7个答案)
16小时前关门了。
大家好,我很想知道为什么代码这样做。

weight = float(input("Weight: "))
KorL = input("(K)gs or (L)bs: ")
if KorL == "K" or "k":
    convert = weight // 2.2
    print("Weight in Kg is: ", convert)
elif KorL == "L" or "l":
     convert1 = weight * 2.2
     print("Weight in Lbs is: ", convert1)

给我看这个

Weight: 45
(K)gs or (L)bs: l
Weight in Kg is:  20.0

在执行"或"运算时,我希望使用"K"或"k"

mzmfm0qo

mzmfm0qo1#

关于或比较的问题已经提出并得到了回答:Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?

适合您情况的比较

要读取预期为单个字母(不区分大小写)的用户输入并对其进行测试,您可以:

  • 使用in成员运算符或将其与列表或集合进行比较
  • 将其小写并与小写字母进行比较(请参见str.lower()
weight = float(input("Weight: "))
letter = input("(K)gs or (L)bs: ")
if letter in {'K', 'k'}:
    inKgs = weight // 2.2
    print("Weight in Kg is: ", inKgs)
elif letter.lower() == 'l':
    inLbs = weight * 2.2
    print("Weight in Lbs is: ", inLbs)

要使用像or这样的布尔运算符,条件或比较都必须写成:

if letter == 'K' or letter == 'k':

另见:

相关问题