我想在另一个函数中使用一个函数的返回值,而不是再次运行该函数。(Python)

Dan*_*ara 3 python return function return-value python-3.x

例如,现在每次我使用 cost = get_cost() 时,该函数都会通过并再次要求输入。有没有办法只保存返回值,以便我可以在另一个函数中使用该值?感谢所有的帮助。

def get_cost():

    cost = float(input('Please Enter the Cost of the Meal: '))

    while cost <= 0:
        print('The Cost Must Be Greater Than 0!')
        cost = float(input('Please Enter the Cost of the Meal: '))
    else:
        return cost

def compute_tip():

    cost = get_cost()

    finalTip = cost * 0.18
    return finalTip

def compute_tax():

    cost = get_cost()

    finalTax = cost * 0.0825
    return finalTax

def compute_grand_total():

    cost = get_cost()    
    finalTip = compute_tip()
    finalTax = compute_tax()

    grandTotal = cost + finalTip + finalTax
    return grandTotal

def display_total_cost():

    cost = get_cost()
    finalTip = compute_tip()
    finalTax = compute_tax()
    grandTotal = compute_grand_total()

    print('Cost\t$', format(cost, '.2f'))
    print('Tip\t$', format(finalTip, '.2f'))
    print('Tax\t$', format(finalTax, '.2f'))
    print('Total\t$', format(grandTotal, '.2f'))


def main():

    get_cost()

    compute_tip()

    compute_tax()

    compute_grand_total()

    display_total_cost()

main()
Run Code Online (Sandbox Code Playgroud)

小智 5

看起来你的主函数只需要包含一个函数调用

def main():
    display_total_cost()
Run Code Online (Sandbox Code Playgroud)

因为display_total_cost()根据需要在内部调用所有其他函数。

然后您可以将cost函数参数作为函数参数传递给需要它的其他函数,并删除get_cost所有其他函数的调用。这是您的脚本的更新版本:

def get_cost():

    cost = float(input('Please Enter the Cost of the Meal: '))

    while cost <= 0:
        print('The Cost Must Be Greater Than 0!')
        cost = float(input('Please Enter the Cost of the Meal: '))
    else:
        return cost

def compute_tip(cost):
    finalTip = cost * 0.18
    return finalTip

def compute_tax(cost):
    finalTax = cost * 0.0825
    return finalTax

def display_total_cost():

    cost = get_cost()
    finalTip = compute_tip(cost)
    finalTax = compute_tax(cost)
    grandTotal = cost + finalTip + finalTax

    print('Cost\t$', format(cost, '.2f'))
    print('Tip\t$', format(finalTip, '.2f'))
    print('Tax\t$', format(finalTax, '.2f'))
    print('Total\t$', format(grandTotal, '.2f'))


def main():
    display_total_cost()

# common practice is to include this line
if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)