+ 3

I don't understand, why result is 6 def func(x): res=0 for i in range(x): res+= i return res print (func (4))

Hi, can anyone explain why result is 6? def func(x): res=0 for i in range(x): res+= i return res print (func (4))

8th Sep 2016, 12:47 PM
Giorgi
15 Antworten
+ 28
for i in range(4) i takes the values from 0 to 3. 0+1+2+3=6
8th Sep 2016, 12:51 PM
Zen
Zen - avatar
+ 20
For i in range(4) i takes the values which are 0,1,2,3. For value 0(it means i=0): res=res+i res=0(it is 0, as you can see its value after def function)+0(i) res=0(we will use this value at the end of "For Value 1") --- For Value 1: res=res+i res=0(which comes from "end of "For Value 0") +1 res=1(our new res value, not 0 anymore) --- For Value 2: res=res+i res=1+2 res=3 -- For value 3: res=res+i res=3+3 res=6
11th Sep 2017, 6:37 AM
Zafer Çiğdem
Zafer Çiğdem - avatar
+ 7
the result becomes zero as the return statement was inside the for loop. the indentation is having a great role in python programming. your program will be like this: def func(x): res=0 for i in range(x): res+=i return res print(func(4)) This is the correct program: def func(x): res=0 for i in range(x): res+=i return res print(func(4))
23rd Jul 2017, 5:59 AM
Delfin Biju
Delfin Biju - avatar
+ 3
Answer is 8
13th Apr 2020, 6:38 AM
Vijaya sarathy P
Vijaya sarathy P - avatar
+ 1
I got really confused on this two. This really, really helps me understand more about the for i in range function too.
5th Jun 2020, 4:50 AM
VanDaMan
VanDaMan - avatar
+ 1
I'm new to this so idk much but I think: i = every argument in x .......so the range of 4 is (0, 1, 2, 3). res = res + 0 res = 0 so its staying the same res = res + 1 res = 1 because 0 + 1 = 1 res = res + 2 res = 3 because res = 1 and 1 + 2 = 3 res = res + 3 res = 6 because res = 3 and 3 + 3 = 6 this is why when you enter print(func(3)) you get 3 instead of 2 even though print(*range(3)) = 2 because you count starting from 0. if you entered 5 for x it would be res = res + 4 (not 5 because you start counting from 0) which would equal 10 since res = 6 from the last line. i = every argument in x hope this helped.
8th Oct 2020, 12:54 AM
Emmanuel Kebede h
Emmanuel Kebede h - avatar
0
Thank you, Zen
8th Sep 2016, 12:57 PM
Giorgi
0
The same code results in zero on the python IDLE. Why? :-/
1st Dec 2016, 4:56 AM
Dheeraj Prakaash
Dheeraj Prakaash - avatar
0
thank you . good explanation
7th Oct 2017, 4:11 PM
Rakes Prasad
Rakes Prasad - avatar
0
thanks
22nd Mar 2018, 2:20 AM
BALA VISAKH V R
BALA VISAKH V R - avatar
0
27th Feb 2020, 3:58 PM
Safiya Khan
Safiya Khan - avatar
0
The loop runs four times 0-3 res += i res = res + i res = 0 + 0 = 0 res = 0 + 1 = 1 res = 1 + 2 = 3 res = 3 + 3 = 6
29th May 2020, 11:22 PM
Ali
0
thank u. was really confused
21st Aug 2020, 6:21 PM
Doris
0
the answer is 8.
15th Aug 2021, 1:29 PM
Sahana ca
Sahana ca - avatar
0
8
20th Dec 2021, 5:00 PM
Ayyoub Chikhi