如何在if语句中选择函数

时间:2019-02-15 06:01:37

标签: python function input

我需要允许用户选择一个值并相应地调用一个函数的帮助。

weight = input('Enter K for kilos  or P for pounds : ')

unit = weight

if unit == "K":

    def metricTopound(kilograms):

        pounds = kilograms * 2.2
        ounces = pounds * 16

        return int(pounds), ounces % 16

        kilograms = float(input("How many Kilos ? "))
        lb, o = metricTopound(kilograms)
        print('The amount of pounds you entered is {}. '\
        'This is {} pounds and {} ounces.'.format(kilograms, lb, o))

elif unit == " P ":

    def poundsToMetric(pounds):
        kilograms = pounds / 2.2
        grams = kilograms * 1000

        return int(kilograms), grams % 1000

        pounds = float(input("How many Pounds? "))
        kg, g = poundsToMetric(pounds)
        print('The amount of pounds you entered is {}. '\
        'This is {} kilograms and {} grams.'.format(pounds, kg, g))

用户应该能够选择P来获取以千克为单位的重量,或者选择K来获取以磅为单位的重量。

2 个答案:

答案 0 :(得分:0)

您可能需要预先定义函数:

def metricTopound(kilograms):
    pounds = kilograms * 2.2
    ounces = pounds * 16

    return int(pounds), ounces % 16

def poundsToMetric(pounds):
    kilograms = pounds / 2.2
    grams = kilograms * 1000

    return int(kilograms), grams % 1000

weight = input('Enter K for kilos  or P for pounds : ')

unit = weight

if unit == "K":
    kilograms = float(input("How many Kilos ? "))
    lb, o = metricTopound(kilograms)
    print('The amount of kilograms you entered is {}. '\
    'This is {} pounds and {} ounces.'.format(kilograms, lb, o))
elif unit == "P":
    pounds = float(input("How many Pounds? "))
    kg, g = poundsToMetric(pounds)
    print('The amount of pounds you entered is {}. '\
    'This is {} kilograms and {} grams.'.format(pounds, kg, g))

答案 1 :(得分:0)

  1. 您输入的类型不正确,应该在上方或单独的文件中进行定义,然后调用该功能
  2. return语句下面的行将永远不会执行
  3. 您正在传递" P "进行比较,因此用户需要先添加空格,然后再添加P和尾随空格。

固定代码

def metricTopound(kilograms):

        pounds = kilograms * 2.2
        ounces = pounds * 16

        return int(pounds), ounces % 16


def poundsToMetric(pounds):
        kilograms = pounds / 2.2
        grams = kilograms * 1000

        return int(kilograms), grams % 1000


unit = raw_input('Enter K for kilos  or P for pounds : ') #get as string

weight= input("Ener Weight") #get as integer

if unit == "K":
       metricTopound(weight)
       kilograms = float(input("How many Kilos ? "))
       lb, o = metricTopound(kilograms)
       print('The amount of pounds you entered is {}. '\
       'This is {} pounds and {} ounces.'.format(kilograms, lb, o))



elif unit == "P":
         poundsToMetric(weight)
         pounds = float(input("How many Pounds? "))
         kg, g = poundsToMetric(pounds)
         print('The amount of pounds you entered is {}. '\
         'This is {} kilograms and {} grams.'.format(pounds, kg, g))