0

I'm having a simple problem but I just can't see where the issue is. I'm simply trying to validate input with an if statement, however for some reason I can't see the test fails. Yes, just a beginner, and I'm sure I'm missing something obvious. I've tried cleaning up the input with strip etc but I've exhausted everything I can think of. Any help will be greatly appreciated.

print("Convert your weight")
while (True):
    try:
        raw = float(input("What is your weight?: "))
    except ValueError:
        print("You must enter a number")
    else:
        break
while (True):
    try:
        unit = str.lower(input("Is that pounds'(L)', or kilos'(K)'?: "))
    except:
        print("It must be a letter")
    else:
        if unit!= "l" or "k":
            print("Unit: " + unit)
            print("You can only input L or K")
        else:
            print("Time to send a break")
            break

print ("raw: " + str(raw) + " : " + "unit: " + str(unit))
davetayl
  • 113
  • 1
  • 7

1 Answers1

1

The problem lies in this line:

if unit!= "l" or "k":

You are comparing two expressions with an or: unit!= "l" and "k". The problem is that the second expression ("k") is always True, so the if-statement will alway be true.

If you want to test if the unit is l or k, I suggest doing the follwing:

if unit not in ['l', 'k']:

If you want to do it your way (which gets tedious when you have more possible values), then you have to do the following:

if unit != "l" and unit != "k":
  • two things changed to your implementation:
    1. You compare the value of unit twice
    2. You need to use and instead of or - with or the expression would always be true, because any character will always fulfil either not being 'k' or not being 'l'
koegl
  • 505
  • 2
  • 13