+ 1
can anyone explain me that why this code will print 6
def func(x): res = 0 for i in range(x): res += i return res print(func(4))
2 Antworten
+ 3
You are using Range(4) so loop will run for the value of i=0, i=1, i=2 and i=3
you are using same variable res to store every time.
so
res= 0+1+2+3
that's why returning 6.
+ 1
# if in doubt of how things work try adding print statements
# at each stage to see how values are changing
def func(x):
res = 0
for i in range(x):
res += i
print('i value = ',i,'new res value = ',res)
print('loop complete final res value =',res)
return res
print('returned vale of res = ',func(4))