磅公斤转换不起作用?

时间:2015-10-12 21:07:39

标签: python python-3.x

amount = int(input("Please enter the mass in lbs you want to convert (without units): "))
if amount == int:
    return (amount / 2.2, "kilograms")

Python说返回是在函数之外? ^^^我做错了什么? 这会更好吗?

def weight():
  a = int()
  a = input("What would you like to convert? ")
  if a == int:
    pounds = input("Enter a number in pounds to convert to kilos: ")
    kilos = pounds * 2.2
    print(kilos)

2 个答案:

答案 0 :(得分:1)

正确的设计应如下所示:

def weight():
        pounds = input("Enter a number in pounds to convert to kilos: ")
        if pounds.isdigit():
                pounds = int(pounds)
                kilos = pounds * 2.2
                return kilos
        else:
                print("Please enter a number next time :D")

print weight()

请勿忘记使用weight()

调用此功能

使用if pounds.isdigit():代替if a == int:if pounds == int:

你有2个小错误,实际上非常好。

答案 1 :(得分:0)

def get_int(prompt):
   ''' like input(prompt) , but guaranteed to return an integer '''
   while True:
       try:
         return int(input(prompt))
       except ValueError:
         print ("Invalid input please enter an integer!")


def weight():
    conv_type = input("What would you like to convert? ")
    if conv_type == 'pounds':
        pounds = get_int("Enter a number in pounds to convert to kilos: ")
        kilos = pounds / 2.2
        return kilos,"kg"