-2

I am writing a program to convert between pounds and kilograms. 1 kilogram is approximately 2.2 pounds. I want to get user input for their weight and if they input 'l' or 'L' then I will return their weight in pounds and vice versa for kilograms. But my 'elif' statement isn't working. My code keeps doing the math for only the first 'if' statement. However, if I completely delete the first 'if' statement, then the 'elif' statement works. I do not know what's wrong. Please help I am learning Python

weight = input("Enter your weight: ")
option = input("(L)bs or (K)g: ")


if(option == 'L' or 'l'):
    actual_weight = float(weight)*2.2
    print("You are " + str(actual_weight) + "kilograms")

elif(option == 'K' or 'k'):
    actual_weight = float(weight)/ 2.2
    print("You are " + str(actual_weight) + "pounds")
hershey10
  • 77
  • 4
  • 1
    There’s bug in your if statement. In the or conditions, latter check is always true in both cases. So you’ll need to refactor code to eliminate the bug. – rv.kvetch Jan 26 '22 at 04:00
  • 2
    Does this answer your question? [How to test multiple variables for equality against a single value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-for-equality-against-a-single-value) – ewokx Jan 26 '22 at 04:00

2 Answers2

2

Corralien's answer is right.

What you should see is that when you say if option == 'K' or 'k'

the interpreter tries to evaluate the two parts on the left and right of the 'OR' and check if they are 'true'

option == 'K' is not true when the input is 'L' but the second part of the OR logic ('k') becomes true and the if statement becomes true.

That is why your first 'if' always work no matter what the input is.

Tharaka Devinda
  • 1,952
  • 21
  • 23
1

The problem is your condition option == 'L' or 'l', it should be option in ['L', 'l'].

Try:

weight = input("Enter your weight: ")
option = input("(L)bs or (K)g: ")

if option.upper() == 'L':
    actual_weight = float(weight)*2.2
    print(f"You are {actual_weight:.2f} kilograms")

elif option.upper() == 'K':
    actual_weight = float(weight)/ 2.2
    print(f"You are {actual_weight:.2f} pounds")
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Corralien
  • 109,409
  • 8
  • 28
  • 52