Is There A Rule of Thumb For Where to Put the Print or Return Statements in a Nested Loop?

I keep getting stuck on exercises where I have the correct code but either the print or the return statement is at the wrong indentation point, and yielding different results than what is expected. I’d really like an explanation of how and why.

Example from the Python Loops challenge

This code returns: [‘Hello, Owen’, ‘Hello, Max’, ‘Hello, Sophie’] which is the intended output.

def add_greetings(names):
  empty_list = []
  for i in names:
    empty_list.append("Hello, " + i)
  return empty_list

print(add_greetings(["Owen", "Max", "Sophie"]))

THIS code returns only [‘Hello, Owen’] and the only difference is the return statement is in line with the append function.

def add_greetings(names):
  empty_list = []
  for i in names:
    empty_list.append("Hello, " + i)
    return empty_list

print(add_greetings(["Owen", "Max", "Sophie"]))

Why is this true and is there a simple way to remember what the rule is for how to indent it?

Since Python indicates code blocks based on indentation, take a look at what block of code the return is a part of:

for i in names:
    empty_list.append("Hello, " + i)
    return empty_list

Remember that a return will end a function, so when it runs matters. If the the for loop uses a return on the first iteration, it won’t be able to iterate through the rest of names.


There isn’t an exact rule on where to put a return or a print() in a function, though there are a few things to keep in mind.

A print() can vary depending on where you put it:

lst = [1, 2, 3]
new_lst = []

for num in lst:
  new_lst.append(num)
  print(new_lst)
#   \
#    Prints three lines, each at a different stage of the for loops iteration

for num in lst:
  new_lst.append(num)
print(new_lst)
#  \
#   Prints one time, once the for loop finishes iterating.

At the same time, one should make sure a for loop does not return until the function has performed every action it is supposed to. This is something illustrated by your current function.

4 Likes