+ 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))
16 Respostas
+ 28
for i in range(4)
i takes the values from 0 to 3.
0+1+2+3=6
+ 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
+ 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))
+ 3
Answer is 8
+ 1
I got really confused on this two. This really, really helps me understand more about the for i in range function too.
+ 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.
0
Thank you, Zen
0
The same code results in zero on the python IDLE. Why? :-/
0
thank you . good explanation
0
thanks
0
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
0
thank u. was really confused
0
the answer is 8.
0
8