12. Printing out a list item by item in a function


#1

The error message I am getting says "You either forgot to call print_list(n) or there is something wrong because 5 wasn't printed." 7 did not print either. Could someone explain what I am doing wrong?

n = [3, 5, 7]

def print_list(x):
    for i in range(0, len(x)):
        return x[i]

print print_list(n)

#2

It's never a good idea to use return in a loop that is expected to iterate over an entire list. The function is not expected to return anything, only print indexed data.

def print_list(x):
    for i in range(0, len(x)):
        print x[i]

print_list(n)

#3

What does a return tell a program to do, in general? Why use return as opposed to print? Also, thank you for the help. That mostly makes sense.


#4

return is for when we want to send data back to the caller.

caller passes x
callee works on x creating y and returning it
caller receives y

It's a two-way communication. The caller passes data from its scope to a function with its own scope, then the function passes data back to the caller scope. This is fundamental stuff. Drill it in.