12/18 - Difference b/w the working of two codes


#1

‘’’
n = [3, 5, 7]
def print_list(x):
for i in range(0, len(x)):
print x[i]
print_list(n)
‘’’
This code gives output as:
3
5
7

‘’’
n = [3, 5, 7]
def print_list(x):
for i in range(0, len(x)):
return x[i]
print print_list(n)
‘’’
This code gives output as:
3

I am not able to understand the difference in their functioning


#2

you don’t understand the difference between return and print?

print is literally that, print to stdout (standard output)

return means return, hand something back. However, a function can only return a single thing, and given return is the last thing a function does means a function will end when a return keyword is reached. Even if this means it has to “break” out of the loop

why use range() here? It complicates matters without adding any value


#3

My confusion wasn’t between ‘return’ and ‘print’. I just didn’t expect to see only one single number when the command involved printing the whole list. But now that you say it can only return one thing, it makes sense. Thanks for the help.
Btw, ‘range()’ was a part of the automatically generated code, so as to learn about its applications.
:grinning:


#4

poor demonstration of the usages of range then by the lesson.


#5

The Problem is that return statement ends your function in the first iteration of your loop

It sees return x[0] the function ends handing x[0] which is 3 to the caller.
If you want to see the whole list you need to print not return in the loop


#6

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