问题
I am making a program that converts your weight from kg to lbs and vice versa. It prompts you to input a weight, asks if it's in kg or lbs, then gives you the result.
The code is as follows:
weight = int(input("What is your weight? "))
unit = input ("(L)bs or (K)g? ")
unit = unit.upper
if unit == "L":
converted = (weight * 0.45)
print(converted)
else:
converted = (weight // 0.45)
print(converted)
The converter is working fine if I put my kg and say it's kg, but when I put my weight in lbs and say it is in lbs, it assumes the value is in kg and gives me the answer in lbs. Can anyone tell me what the issue is?
回答1:
You should add '()' to the end of unit.upper.
Without '()', you are not calling the upper method, but only referencing it.
unit.upper will return ('built-in method upper of str object at 0x00630240'),
and so, when you set unit = unit.upper,
you are actually setting unit = 'built-in method upper of str object at 0x00630240',
which activated the else statement.
weight = int(input("What is your weight? "))
unit = input ("(L)bs or (K)g? ")
unit = unit.upper()
if unit == "L":
converted = (weight * 0.45)
print(converted)
else:
converted = (weight // 0.45)
print(converted)
来源:https://stackoverflow.com/questions/61860901/if-statement-problem-about-a-small-converter-i-made