Prince Prince - 1 year ago 98
Python Question

return statement vs. print statement?

Can someone explain why this code only prints 6? :)

def func(x):
result = 0
for i in range(x):
result = result + i
return result


Answer Source

In your code, you were simply adding up the integers from [0,4) (i.e. 0+1+2+3=6), that's why it only prints 6 when you call printf(func(4)).

If you call print(func(1)) the range would be [0,1) meaning it's just 0, so that statement will only print 0.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download