 Indentation level of `return`

Question

As per this lesson Python Loops Challenge: Divisible by ten. What indentation should return be at?

Solution

When using return to leave a function, it is important to have it at the correct level of indentation. When a line with return is run, the entire function will cease running and will output what followed the return. Normally, this isn’t too tricky, just put it at the end of your function right?

Def my_function():
do stuff
return thing

But what if you have a loop like for or while in your function? What level does the return need to be at? The below quote from mtf details an explanation of this.

When he refers to above, think of a function that you want to iterate through every item in a list (like in the original lesson).

I hope this helps everyone with this concept, if you are still having challenges please discuss below.

1 Like

Hello CC Moderator:

I have not used Count variable as most of the people here did (although I realize that it is simpler).

I have used the following to return the amount of numbers that are divisible by 10:

list_w_num_by_10 = []
def divisible_by_ten(nums):
for number in nums:
if number % 10 == 0:
list_w_num_by_10.append(number)
return
len(list_w_num_by_10)

print(divisible_by_ten([20, 25, 30, 35, 40]))
print(list_w_num_by_10)
# prints:
None


I do not understand why .append(number) is not adding number that satisfies the if statement into the list_w_num_by_10 list? It returns None even though there should be at least one number, 20, given the second print call.

Thank you for your insight!

2 Likes

This should be initialized inside the function so it is an empty list each time the function is run.

Be sure to unindent out of your loop before returning.

return len(...)

Note that return by itself is the same as not having a return. In either case it will return None.

2 Likes

Hello @mtf !

Thank you for your prompt attention and reply!

This should be initialized inside the function so it is an empty list each time the function is run.

Be sure to unindent out of your loop before returning.

I did that (sorry - it was my typo that len() was unindented initially).

Result now returns 1 and I don’t know why?
Could you, please also briefly explain why list_w_num_by_10 = [] had to be defined within the function? Does it matter in this case whether it is defined globally or locally within divisible_by_ten function if .append() will change that list anyway?

Thank you for your time and further help!

1 Like

Because each time we call the function, we want to start with an empty list to accumulate to (or a counter, alternatively).

A counter would be more practical since it is a single value, rather than a data structure. It is likely quicker to add 1 than to append to a list then poll the length. However, for this exercise, either should be fine.

3 Likes

Hi

Could someone help me? I dont understand why my code below only returns 1 when it should be returning 3?

def divisible_by_ten(nums):
count = 0
for num in nums:
if num % 10 == 0:
count=+1
return count

#Uncomment the line below when your function is done
print(divisible_by_ten([20, 25, 30, 35, 40]))

Without being able to tell, for sure, this sounds like a return inside the loop. Unindent the return line so it matches with count = 0.

1 Like

When I use the following code the output is 1 - the correct answer is 3:

#Write your function here
def divisible_by_ten(nums):
count = 0
for number in nums:
if (number % 10 == 0):
count += 1
return count

#Uncomment the line below when your function is done
print(divisible_by_ten([20, 25, 30, 35, 40]))

The below is the code from the solution. The only difference is the indentation of the return count line. Why would the more indented line run the code over less numbers?
TIA

#Write your function here
def divisible_by_ten(nums):
count = 0
for number in nums:
if (number % 10 == 0):
count += 1
return count

#Uncomment the line below when your function is done
print(divisible_by_ten([20, 25, 30, 35, 40]))

Peter, any return statement does two things:

1. Places the return value in memory - where it can be grabbed by the calling statement and assigned to a variable or used in another function.

2. Halts the execution of the function. Once return is called one time, the function is terminated.

2 Likes

Ok. I get the first part.

But in this instance when return is indented to a different degree it halts the function at different points.

So when it is indented such that it sits within the IF clause it halts the function after one IF iteration and when its indented such that it its outside the IF clause and underneath the FOR clause, the FOR clause does run through all the elements and does not halt?

A colon represents the opening of a new block, hence the indent to isolate it from the current block (the one containing the signature line). When a return is encountered anywhere in the code, the function ceases and program flow resumes at the caller.

Sometimes, as above, we want and expect the loop to fully iterate the object without exiting the function. The return would be outside of both the if and the for..in blocks, and would be written in the same block as the for signature line.

for ...:
if ...:
# ...
return ...
3 Likes

You need to carefully follow the logic of the code. When return is reached ONE TIME, the function terminates. The key is to keep track of when you are in a loop, and when out. Learn how to read “blocks”, as @mtf described above.

if does not iterate (move sequentially from one value to the next). An if statement may or may not execute, depending upon whether its condition returns True. If it executes, and a return statement is lurking beneath it, the function will halt.

for loops, on the other hand, do iterate. Sometimes there are if statements beneath them. If, during one of the iterations, one of those if conditions returns True, and leads to return, again, the function halts.

1 Like

What?
I was running my function thinking this must be right!
It returned 1 so i thought i had messed up. After throwing myself at it over and over i gave up, copied my code and pressed solution. Well isn’t that a slap in the face. What am I missing. Am I blind or does the exact same code return different results?

[Edit: it returns 3 and 1 in notepad++ too, seriously I can’t see it, what is the error?

1 Like

The second example has an over-indented return line.

1 Like

Check line no 18 you are calling return under for loop , one space extra resulted this error