+ 7
Please explain how this program works ^_^::
def func(x): res = 0 for i in range(x): res += i return res print(func(4))
2 Antworten
+ 10
Pretty margaret
Look at it this way ::
================
def func(x):
defines a function func()
that takes in an argument "x";
next :: res =0;
declares a variable "res" and sets it to 0
for i in range(x):
declares a for loop, using "i" as the control variable.
Here, i starts at 0 and increases by 1,till it gets to (x-1), which in this case is (4-1).
Note::: i stops at x-1, not x.
So the range becomes
0,1,2,3
next :: red +=i ;
each time the loop runs, the value of "i" gets added to "res".
so if you call func(4),
it is the same as saying
i =0
res +=0; res= 0
i=1
res +=1; res= 1
i=2
red +=2; res =3
i=3
res += 3; res=6
+ 12
Make sure you indent your code blocks after the colons or it won't work 😉
def func(x):
res = 0
for i in range(x):
res += i
return res
print(func(4))