can someone explain me how does this code works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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))

7th Jul 2016, 5:30 AM
Thu Rein
Thu Rein - avatar
4 Answers
+ 1
well, it will print 6 (1+2+3, not including 4)
7th Jul 2016, 5:53 AM
Zedd Zhou
Zedd Zhou - avatar
+ 1
my pleasure 😀
7th Jul 2016, 6:00 AM
Zedd Zhou
Zedd Zhou - avatar
0
Thanks so much, I see now.
7th Jul 2016, 5:56 AM
Thu Rein
Thu Rein - avatar
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
7th Jul 2016, 7:12 PM
zak