0
can someone explain me how does this code works?
def func(x): res = 0 for I in range(x): res += I return res print(func(4))
4 Answers
+ 1
well, it will print 6 (1+2+3, not including 4)
+ 1
my pleasure đ
0
Thanks so much, I see now.
0
this code basically define a function"func" that takes an argument "x".
inside it, the variable res is initialized with the value 0.
we iterate over a range of numbers from 0 to x-1 (range don't include the last number) because writing "range(x) is the same as range(0,x), x is the last number.
we add 1 on to res in every iteration.
when we exit the loop the variable res is returned.
finally we print the value of func(4).
the value of func(4) is the value of the variable "res" it returned