0

[python functions]calculation sequence when "return" nested in for loop

what's the differences between the following two functions: [func1] def func(x): res = 0 for i in range(x): res += i return res print(func(4)) [func2] def func(x): res = 0 for i in range(x): res += i return res print(func(4)) func1 output is 0 and func2 outputs 6.BUT as referenced to the tutorial "Once you return a value from a function, it immediately stops being executed. Any code after the return statement will never happen." I assume both functions end up with :res=0, i=0, thus res+=i outputs 0.

5th Sep 2017, 9:38 AM
Ren Li
Ren Li - avatar
2 Réponses
0
in func1, return is nested in for loop. so fort value of i = 0, res=0 and return 0 => break for loop in func2, return is after for loop. so i=0=> res=0;i=1=>res=1;i=2=>res=3 and i=3=> res=6 i=4 => break for loop next action is return res => output 6
5th Sep 2017, 9:49 AM
MBZH31
MBZH31 - avatar
+ 3
Indentation is the difference. In the firs function it stops in the first iteration, because return comes there inside the for loop. Never ever use return inside the for loop!!!
5th Sep 2017, 10:02 AM
Saidmamad Gulomshoev
Saidmamad Gulomshoev - avatar