Я хотел бы использовать возвращаемое значение функции в другой функции, без повторного выполнения этой функции. (Python) - PullRequest
3 голосов
/ 16 октября 2019

Прямо сейчас каждый раз, когда я использую 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()

Ответы [ 3 ]

4 голосов
/ 16 октября 2019

похоже, ваша основная функция должна включать только один вызов функции

def main():
    display_total_cost()

, потому что 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()
0 голосов
/ 16 октября 2019

Добавьте параметры, чтобы вам больше не приходилось вызывать одни и те же функции.

    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 compute_grand_total(cost, finalTip, finalTax):

    grandTotal = cost + finalTip + finalTax
    return grandTotal

def display_total_cost(cost):

    finalTip = compute_tip(cost)
    finalTax = compute_tax(cost)
    grandTotal = compute_grand_total(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():

    cost = get_cost()

    display_total_cost(cost)

main()
0 голосов
/ 16 октября 2019

Вы должны сохранить значение после его возвращения и передать его другим функциям. Примерно так:

def main():
    cost = get_cost()
    tip = compute_tip(cost)
    tax = compute_tax(cost)
    total = compute_grand_total(tip, tax)
    display_total_cost(total)

Но вам также придется переписать функции, чтобы принять эти аргументы, например:

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