I was expecting different answer like 0 1 3 6 But the answer is only 6.Could someone help me understand it please, Thanks!
def func(x):
res = 0
for i in range(x):
res += i
return res
print(func(4))
I was expecting different answer like 0 1 3 6 But the answer is only 6.Could someone help me understand it please, Thanks!
def func(x):
res = 0
for i in range(x):
res += i
return res
print(func(4))
return
returns only one value. What you meant to use is yield
:
def func(x):
res = 0
for i in range(x):
res += i
yield res
This is called a generator. You may use next to see values one by one, or use * operator to print them all at once:
print(*(func(4)))
Sure enough, you get the desired output:
0 1 3 6