Python Forum

Full Version: Help with basic weight converter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Ok so I'm brand new to coding and following a YouTube video for learning python, one of the exercises is to make a simple weight conversion program. I thought I understood it but I'm at a complete loss. The user enters their weight, then it asks if that was in kgs. or lbs. if the user enters a k (higher or lower case) then it will convert to lbs and vice versa. Now the problem I'm having is that the script runs but only outputs the first if statement. I have no idea why. This is my code

weight = float(input("Enter your weight "))
unit = input(" Is that (K)Kgs or (L)lbs ")
conversion = 0.45
if unit == "K" or "k":
    convertlbs = (float)(weight * conversion)
    print (convertlbs)
elif unit == "L" or "l":
    convertkgs = (float)(weight / conversion)
    print (convertkgs)
else:
    print ("wrong input")
Could someone please explain why this is not working? From what I understand the first if statement is checking to see if the user input for unit is equal to K or k, if it is then it should times their weight by 0.45, if its not true then it should move onto the next if statement to see if its an L or l, then dividing my 0.45. If neither of these inputs are true then it should print wrong input
Non-empty strings, e.g. "k" on line 4 evaluate to True, so your or expression is wrong. The right hand side needs to check unit == "k".
(Jun-29-2022, 02:16 PM)ndc85430 Wrote: [ -> ]Non-empty strings, e.g. "k" on line 4 evaluate to True, so your or expression is wrong. The right hand side needs to check unit == "k".

I can't believe it was that simple! makes perfect sense now that I can see it. I've been pulling my hair out for about an hour with this
"or" is a logical operator. You are trying to use it more like a union.

"k" or "K" tests if "k" is true-ey. If so it returns "k". If not it returns "K". Most objects in Python are true-ey. Python objects that are false-ey are False, None, 0, and empty collections. "k" is a non-empty string, so it is true-ey, and "k" or "K" returns "k".

"and" is similar. "k" and "K" returns "K" if both "k" and "K" are true-ey, else it returns False. Both "k" and "K" are non-empty strings, so "k" and "K" returns "K".

You want to test if unit == "k" or unit == "K". You could also force unit to be upper or lower case: unit.upper() == "K" or you could test if unit is in a collection: unit in ("k", "K"). You might also see: unit in "kK", but this would return True if the user entered "k", "K" or "kK".