+ 2

Could anyone please explain how this code results in 6?

def func(x): # defining a function called func that takes one arguemnt res = 0 # initial value of the variable res is zero for i in range(x): # for every instance within the range from zero to x res += i # res = res + i but what does it mean? return res # return latest value of res print(func(4))

3rd May 2020, 2:43 PM
Visnu Pritom Chowdhury
6 Respostas
+ 5
for i in range(x) that means from i =0 up to i <x (up to x-1), without x. Then you get 0+1+2+3 = 6 You can check it if you in this loop print variable i.
3rd May 2020, 2:54 PM
JaScript
JaScript - avatar
+ 4
Sure here is the explanation :)) You are passing the 4 as the argument of the function. So the value of x becomes 4. Therefore the loop will run for times. Now in each step we are adding the 'i' with res variable. So it goes like : 0+0 (res = 0, i = 0) 0+1 (res = 1, i = 1) 1+2 (res = 3, i = 2) 3+3 (res = 6, i = 3) So the final value for res is 6!
3rd May 2020, 2:51 PM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 1
Thank you guys for your kind elaboration on this matter. I hope you all remain safe and well!
4th May 2020, 1:31 PM
Visnu Pritom Chowdhury
0
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 that's the basic stuff I assumed he knew about like for i in range and return ,you could provide an explanation instead of telling me to
3rd May 2020, 2:57 PM
Abhay
Abhay - avatar