0

What is the output of this code ?

Hello everyone, i would be needing help to understand this one. def func(x): res = 0 for i in range(x): res += i return res print(func(4)) I don't understand how this code works.

1st Jan 2020, 11:07 AM
Anis BEN JABALLAH
Anis BEN JABALLAH - avatar
2 Answers
+ 2
for in range means that the looping starts from 0 to n-1. Since the starting value is not given, it is 0 by default and only one parameter is passed which is taken as the limit. 0 in range 4 //true so res=0+0=0 1 in range 4 //true so res=0+1=1 2 in range 4 //true so res=1+2=3 3 in range 4 //true so res=3+3=6 4 in range 4 //false & loop terminates. So the returned value is 6 and is printed.
1st Jan 2020, 11:35 AM
Avinesh
Avinesh - avatar
0
Thanks for responding. I understand your logic but when i execute the code the output is like this : 0 in range 4 // func(0) = 0 1 in range 4 // func(1) = 0 2 in range 4 // func(2) = 1 3 in range 4 // func(3) = 3 4 in range 4 // func(4) = 6
1st Jan 2020, 11:45 AM
Anis BEN JABALLAH
Anis BEN JABALLAH - avatar