This is a basic program which converts the user's givenWeight
into another unit. 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)
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? ")