首页 > 解决方案 > IF ELSE 语句在 python 中不能正常工作

问题描述

我是 Python 新手,并试图通过使用if,else语句创建一个权重转换器。

这应该要求用户以磅 (lbs) 或千克 (kgs) 为单位输入重量和单位并进行转换,但程序仅执行if条件。

这是我的代码片段:

weight = int(input("Weight = "))
unit = input('(L)bs or (K)')
if unit == "L" or "l":
  print(f'You are {weight*0.45} kilograms')
elif unit == "K" or "k":
  print(f'You are {weight*2.2} pounds')
else:
  print('The converter is only for Kgs and Lbs')

这是一个屏幕截图:

在此处输入图像描述

标签: python-3.x

解决方案


您需要在两行中进行更改:

weight  = int(input("Weight: "))
unit    = input("(L)bs or (K): ")

# if unit == "L" or "l":    # OLD_LINE
if unit == "L" or unit == "l":  # NEW_LINE
    print(f"You are {weight*0.45} kilograms")

# elif unit == "K" or "k":  # OLD_LINE
elif unit == "K" or unit == "k":    # NEW_LINE
    print(f"You are {weight*2.2} pounds")

else:
    print("The converter is only for Kgs and Lbs")

请参阅参考资料


推荐阅读