0

I'm studying python from scratch and I have a really trivial question. I want to write this program in which input my weight and the unit (Lbs or Kg) and then get the conversion:

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

All is fine when I choose "L" as unit but when I type "K" the program divides instead of multiplying (like if I typed "L") and I don't get why. What's wrong in my code? Thank you for your help.

Baffo
  • 61
  • 5
  • 1
    Need to remove the "l" – difurious Aug 26 '20 at 21:29
  • Remove `or "l"` from your `if`. See https://docs.python.org/2.4/lib/truth.html – PM 77-1 Aug 26 '20 at 21:31
  • In this case it could not be `"l"` because you have converted to upper case. But more generally this is not the way to test whether an expression has one of several values.You would use `if unit.upper() in ("L", "LB"):` for example. – alani Aug 26 '20 at 21:34
  • 1
    Does this answer your question? [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Jongware Aug 26 '20 at 21:38

3 Answers3

0

Remote the " or "l"" portion from your code. The if statement is currently evaluated as (unit.upper() == "L") or ("l"), and "l" evaluates to true, so the elif is never reached.

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")
Evan Baldonado
  • 348
  • 1
  • 2
  • 13
0

You are using the if statement wrong. In case you wanted to compare 2 chars, you should do it like this:

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

But since you use the .upper() method, you just need to remove the "l" from your if statement, getting this result:

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

Always be sure to check all your conditions in your "if".

Edgedancer
  • 127
  • 9
-1

Need to remove the "l" as it'll just get returned.

You can see this by just running

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

output

'l'

If something is returned in Python it's counted as "True" (excluding exceptions such as "None" or 0)

difurious
  • 1,523
  • 3
  • 19
  • 32