Home > OS >  python WeightConverter using functions
python WeightConverter using functions

Time:07-08

I am improving upon a basic weight converter I had made using if-elif statements, I am only a beginner, so please don't throw many advance concepts at me. Here's the code. Something is going wrong in the else statement, where after the user gives an invalid value, the program asks for the value again, but returns none insead of the expected result

givenWeight = int(input("Weight? "))  
unit = input("lbs or kgs? ") 
converted = 0


def convertWeight(weight, unit):
    if unit == "lbs":
        converted = f"{weight * 0.454} kgs"
        return converted
    elif unit == "kgs":
        converted = f"{weight * 2.205} lbs"
        return converted
    else:
        print("Invalid unit")
        unit = input("lbs or kgs? ") 
        convertWeight(givenWeight, unit) # recalls function to convert weight


output = convertWeight(givenWeight, unit)
print(output)

CodePudding user response:

The recursive call to convertWeight after your else statement is only returning the string value to that point in the code. Also note that your global variable converted is both unnecessary and not the same object as the variable in the function. Why not use something simple.

def convertWeight(weight, unit):
    while True:
        if unit == "lbs":
            converted = f"{weight * 0.454} kgs"
            return converted
        elif unit == "kgs":
            converted = f"{weight * 2.205} lbs"
            return converted
        else:
             print("Invalid unit")
             unit = input("lbs or kgs? ")
  • Related