0
defining function in python
What is the output of this code? def func(x): res = 0 for i in range(x): res += i return res print(func(4))
3 Answers
+ 6
Nitesh Kumar
Oh sorry, my mistake.
So the number 4 is passed to the "func" function and in there the is a "res" var set to 0.
range(x) is now range(4) which means "more or equal than 0 but less than 4".
So the loop begins and 0 is added to res (res = 0 + 0 = 0), the loop continues and 1 is added to res (res = 0 + 1 = 1), then 2... (res = 1 + 2 = 3) and finally 3... (res = 3 + 3 = 6).
Once "i = 4" it is now outside of the defined range so the loop is exited.
The value of res (6) is returned by the function where func(4) originally was, so:
print(func(4));
evalutes to...
print(6);
and 6 is printed.
+ 3
6...
But you could have just run this in the Sololearn's development environment to see that...
https://www.sololearn.com/discuss/1316935/?ref=app
or look at the Python tutorial...
0
but i didnt get how 6 would be printed