【发布时间】:2020-02-13 16:25:46
【问题描述】:
例如,现在每次我使用 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()
【问题讨论】:
-
您可能需要考虑将
cost传递给需要它的函数,这样您就不需要一次又一次地调用get_cost()函数。
标签: python python-3.x function return return-value