-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))
khelwood
  • 55,782
  • 14
  • 81
  • 108
Yrkeb
  • 9
  • 1
  • 1
    the print prints whatever your function returns. unless you `yield` the function can only return _one_ value. Why would it print 0 1 3 6 ? - you would need to print _inside_ the loop the actual `res` (before incrementing) to get these numbers, but then they'll be on seperate lines unless you specify `end=" "` for your print... - your function does essentially a `return sum(range(x))` – Patrick Artner Nov 17 '18 at 11:36
  • You add up the numbers in `range(4)` and get `0+1+2+3==6`. How did you expect it to work? – khelwood Nov 17 '18 at 11:37
  • see https://docs.python.org/3/tutorial/controlflow.html#for-statements for a short overview about `for` and ``range` – Patrick Artner Nov 17 '18 at 11:40
  • thanks guys, I appreciate deeply! – Yrkeb Nov 21 '18 at 20:47

1 Answers1

1

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
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • thanks. but I am new to python. can you explain it in simple way please. thanks. – Yrkeb Nov 17 '18 at 12:53
  • @Bekry A `generator` is like an iterable, but generates (yields) elements on demand. See [this](https://stackoverflow.com/questions/1756096/understanding-generators-in-python) for more on the topic. – Aykhan Hagverdili Nov 17 '18 at 13:08