如何打印多个函数的返回值?

How do you print returned values from multiple functions?

我有一个用于转换简单指标的程序。我是 python 的超级菜鸟,需要一点帮助。

def main():
    use_menu()
    if feet_inches():
        

def use_menu():
    get_menu()
    selection = int(input('Please make a menu selection:'))
    if selection == 1:
        feet_inches()
    elif selection == 2:
        yards_feet()
    elif selection == 3:
        miles_yards()
    elif selection == 4:
        miles_feet()


def get_menu():
    print('1. Convert feet to inches')
    print('2. Convert yards to feet')
    print('3. Convert miles to yards')
    print('4. Convert miles to feet')
    print('5. Exit')


def feet_inches():
    feet2inches = int(input('Enter the number of feet:'))
    answer1 = feet2inches / 3
    return answer1


def yards_feet():
    yards2feet = int(input('Enter the number of yards:'))
    answer2 = yards2feet * 3
    return answer2


def miles_yards():
    miles2yards = int(input('Enter the number of miles:'))
    answer3 = miles2yards * 1760
    return answer3


def miles_feet():
    miles2feet = int(input('Enter the number of miles:'))
    answer4 = miles2feet * 5280
    return answer4


main()

如何在主函数中打印返回值?当我尝试将 answer1 设置为 main 函数中的变量时,我不断收到未解析的引用。我也在为如何为此编写 if/elif 而苦苦挣扎。我们将不胜感激。

第 3 行:

if feet_inches():

下面没有条件动作。

您可以尝试这样的操作:删除上面的第 3 行。

def use_menu():
    get_menu()
    selection = int(input('Please make a menu selection:'))
    if selection == 1:
        fi = feet_inches()
        print(fi)
    elif selection == 2:
        yf = yards_feet()
        print(yf)
    elif selection == 3:
        my = miles_yards()
        print(my)
    elif selection == 4:
        mf = miles_feet()
        print(mf)

您也可以在 use_menu 中使用 return 语句。然后将答案设置为等于 return 在主函数中由该函数编辑的结果。

def main():
    answer = use_menu()
    print(answer)


def use_menu():
    get_menu()
    selection = int(input('Please make a menu selection:'))
    if selection == 1:
        return feet_inches()
    elif selection == 2:
        return yards_feet()
    elif selection == 3:
        return miles_yards()
    elif selection == 4:
        return miles_feet()

您可以按如下方式更改代码:

def main():
    # First, retrieve function to be applied
    func = use_menu()
    if func is not None:
        # Apply function - Could be done in one liner
        res = func()
        print(res)
    

def use_menu():
    get_menu()
    selection = int(input('Please make a menu selection:'))
    if selection == 1:
        return feet_inches
    elif selection == 2:
        return yards_feet
    elif selection == 3:
        return miles_yards
    elif selection == 4:
        return miles_feet
    else:
        return None