KrisKringle
KrisKringle

Reputation: 9

Python "return" difficulties

First, let me say I have done thorough research trying to understand. But I do not understand the explanations that others have given (which is understood by those who asked the question). This is the code I have problems with:

def tax(bill):
    """Adds 8% tax to a restaurant bill."""
    bill *= 1.08
    print "With tax: %f" % bill
    return bill

def tip(bill):
    """Adds 15% tip to a restaurant bill."""
    bill *= 1.15
    print "With tip: %f" % bill
    return bill

meal_cost = 100
meal_with_tax = tax(meal_cost)
meal_with_tip = tip(meal_with_tax)

When I delete the first "return bill" and run it, I get the first number but there is an error when it tries to calculate the second number. The def tax(bill) takes 100 and outputs 108 right? So if I delete the first "return bill", then why is def tip(bill) not doing it's calculations with 108 instead of giving an error?

I really have a problem with grasping the most basic concepts of programming. I've been learning intensely for 3 months now and this is where I am. It is a very slippery subject for my mind to grasp and I would really appreciate some help.

Upvotes: 0

Views: 119

Answers (1)

Robert Lacher
Robert Lacher

Reputation: 656

I believe you're misunderstanding the difference between a return and print statement.

In your tax(bill) function, you're multiplying bill *= 1.08. You then print the value of bill. print only outputs the value of bill to the console window -- it doesn't store that value or allow it to be used by other functions in any way.

The return statement that you're deleting returns the value stored in bill, 108, to the caller. The caller in this instance is meal_with_tax = tax(meal_cost). This means that the value of meal_with_tax is the return value of tax(bill). When you delete return bill, you're returning a value of None, so the value of meal_with_tax is None. You want to return bill so that you assign the value 108 to meal_with_tax.

The reason that tip(bill) returns an error is because it's attempting to calculate None *= 1.15. The value of bill inside tip(bill) is not 108 as you think.

Upvotes: 1

Related Questions