I am confused by "return"


#1

https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/1/4?curriculum_id=4f89dab3d788890003000096

I don't understand when to use "return total" in the "for" loop.

In the first try, I put "return total" at the end of the "for" loop, but it says errors. So I remove it, and it works. But I am still confused about when we should put the "return..." at the end of the "for" loop.


prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]

total = 0
for item in prices:
    total = total + prices[item] * stock[item]
    return total
print total

In the last section, there is an example of code as follow:

def count_small(numbers): 
     total = 0 
     for n in numbers:
         if n < 10: 
             total = total + 1 
     return total 
lost = [4, 8, 15, 16, 23, 42] 
small = count_small(lost) 
print small

I think I mix the "def" and " for" in terms of "return" function.

So in what situation do we use "return"?

Thank you!


#2

We can only use return inside a function. This line will raise an exception.

There are cases where the return statement may appear inside a loop, but in general terms, we expect it at the end of the function, and not inside a control flow structure. Your second code sample if a perfect example of this usage.


#3

Is it necessary to put "return" statement at the end of the function?
What does it use for? Is it for representing an end of a function section?
What if there is no "return" statement in the second code example?


#4

No return is None to Python if the return is examined. A return statement is only needed when data is being passed back to the caller.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.