How come this equals 6? | Sololearn: Learn to code for FREE!

0

How come this equals 6?

Hi, I’m baffled by one of the module questions which was as followed: def fun(x): res = 0 for I in range(x): res += I return res print(func(4)) Output: 6 One final thing, I played around with it in the code playground and I tried 5 and the answer was 10. Please could someone explain how this happens? Many thanks

2/15/2019 7:14:45 PM

Zak Polley

2 Answers

New Answer

+7

#Your code will explain itself as follows def func(x): print('Input',x) res = 0 print('output starts with',res) for I in range(x): print('add',I,'to',res,end=' ') res += I print('=',res) return res print(func(4))

+2

It explains by the thing that "for" function takes all numbers from 0 to the range, in that case 4, but not including 4. The syntax from C++ will explain it better for(int i = 0; i < 4; i++). When i hits 4 it returns false, because 4 can't be smaller than 4, and the loop breaks without doing nothing more. If there would be i<=4, then 4 will be included.