-2

I'm currently learning Python and I'm doing an exercise in which I'm making a weight converter. I keep on running into this issue, can any1 plz help?

weight = int(input("How much do you weigh? "))
unit = input("Was that in (K)gs or (L)bs? ")

if unit == "L" or "l":
    converted = weight * 0.45
    print("Kgs: {0}".format(converted))

if unit == "K" or "k":
    converted = weight / 0.45
    print("Lbs: {0}".format(converted))

The terminal just prints both. I have no idea what the problem is.

Roy2012
  • 11,755
  • 2
  • 22
  • 35
helplz
  • 9
  • you need to use `elif` otherwise both conditions will be evaluated. In addition, you are not using properly `or`, so that is why you always get printed that. – lmiguelvargasf Jul 11 '20 at 18:03
  • You need `if unit == "L" or unit == "l"`. Right now it is doing `if (unit == "L") or ("l")` and `"l"` evaluates to `true`. (Note that in Python, *most* values convert to `true` when converted to booleans. For strings, lists, and other collections of objects, usually the only state that evaluates to `false` is an empty string, or an empty list.) – Trevor Galivan Jul 11 '20 at 18:05
  • I am downvoting because your title is not useful and somewhat disrespectful of the people that come to help here voluntarily. – Mad Physicist Jul 11 '20 at 18:07

2 Answers2

2

Update your code to:

weight = int(input("How much do you weigh? "))
unit = input("Was that in (K)gs or (L)bs? ")

if unit in ["L", "l"]:
    converted = weight * 0.45
    print("Kgs: {0}".format(converted))

elif unit in ["K", "k"]:
    converted = weight / 0.45
    print("Lbs: {0}".format(converted))

You are facing basically two problems:

  1. You need to use if ... : elif ...:. Otherwise, the conditions will be always evaluated.

  2. You are not using or properly. unit == "L" or "l" will be always evaluated to True, what you want to check is whether your input is "k" or "K", so you have some alternatives:

  • unit in ["K", "k"]
  • unit == "k" or unit == "K"
  • unit.tolower() == "k"
  • unit.toupper() == "K"
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
1
if unit == "L" or unit ==  "l":
    converted = weight * 0.45
    print("Kgs: {0}".format(converted))

elif unit == "K" or unit == "k":
    converted = weight / 0.45
    print("Lbs: {0}".format(converted))
kwehmeyer
  • 63
  • 8