0

Why the outpot of this code is 6?

Hi this is the last question of the module 3 exam and I dont understand why its answer is 6 What is the output of this code? def func(x): res = 0 for i in range(x): res += i return res print(func(4)) result 6

23rd Apr 2020, 2:40 PM
Guillermo González
6 Respuestas
+ 4
The first iteration: 0+0=0 The second iteration: 0+1=1 The third iteration: 1+2=3 The fourth iteration: 3+3=6 The answer is 6. for i in range(6): # some code Means the following: Start from 0 and end with 3 The last number doesn't turn on. I hope, it will help 😊👍
23rd Apr 2020, 3:08 PM
F L a Z z Y
F L a Z z Y - avatar
+ 5
It works like this,,,,-- for i in range(4): res = 0 + i res = 0 + 0 + 1 + 2 + 3 [range(4)->0123] res = 6 return res thus it returns 6
23rd Apr 2020, 2:45 PM
M Tamim
M Tamim - avatar
+ 2
Hay bro see you had created a function to create a range and add all the elements of range so according to that when you entered 4 then it created a range of 3 no. I.e. 1,2 and 3 {last element is not counted while creating a range for ex range(1,3) will result in 1,2 and 3 will not be taken} so the sum of all the 3 no. Is 6 so it gives result as 6 .
23rd Apr 2020, 2:45 PM
Ayush Kumar
Ayush Kumar - avatar
+ 2
for i in range(4), we have looping values of i as: 0,1,2,3 On first loop we have : res=res+i (on substituting this simplifies as: 0=0+0)#res=0 Then, 2nd loop: 0=0+1 #res=1 then, 1=1+2 #res=3 At last, 3=3+3 >>res=6<< If you have trouble understanding this you may refer to comments of that question.
23rd Apr 2020, 2:56 PM
Tricker
+ 1
It returns the sum of the inputs. If you want to check. Change the input there to 10... See what the result is
24th Apr 2020, 11:59 AM
Umunnakwe Ephraim Ekene
Umunnakwe Ephraim Ekene - avatar
0
thank you every one, I can understand a little more now
24th Apr 2020, 9:04 PM
Guillermo González