+ 1

Different results when using for loops in a function in python

When I use a for loop outside a function, it gives me a result. But when I use a for loop inside a function, it gives me a different result. And I need to know why. Example: list_1=[1,2,3,4,5} def add_list(list): n=0 for i in list: n=n+i return(n) print(add_list(list1)) >>>Result: '15' n=0 for i in list1: n=n+i print(n) >>>Result: 1 3 6 10 15

25th Aug 2017, 7:48 PM
Mohammed Abdulhady
Mohammed Abdulhady - avatar
4 Respuestas
+ 2
list_1=[1,2,3,4,5] def add_list(list): n=0 for i in list: n=n+i return(n) # here return is OUT the for loop # then return a single value of n print(add_list(list_1)) #################### list_1=[1,2,3,4,5] n=0 for i in list: n=n+i return(n) # here return is within the for # so each iteration # return a value of n Hope it helps you, Be pacient and keep coding.
25th Aug 2017, 8:36 PM
AldoS
AldoS - avatar
+ 1
inside you use "return (n)" , while outside "print (n)" and it is in the loop "for". mind indention!
25th Aug 2017, 8:06 PM
yuri
0
Thank you, but even if I used indention like the following: def add_list(list): n=0 for i in list: n=n+i return(n) print(add_list(list1)) >>>Result: '1' and even if I replaced the "return" with "print", it won't differ. why so?
25th Aug 2017, 8:11 PM
Mohammed Abdulhady
Mohammed Abdulhady - avatar
0
Your function computes the sum of the list elements whereas the other code snippet prints every intermediate result as well. The final sum (15) is the same for both, but your code is not! Edit: If you take print(n) out of the for loop in the snippet it will also just print the final sum.
25th Aug 2017, 8:17 PM
Pieter Schutz