IF statement problem about a small converter I made

谁说我不能喝 提交于 2020-05-30 04:09:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!