0

I want to generate something like that in a function that receives 1 argument n using yield to generate:

      1
     1+2
    1+2+3
      …
      …
1+2+3+⋯+n−1+n

That is my last try:

def suite(n):
    total = 0
    for i in n:
        total+=i
        yield total

and this is what I receive:

Traceback (most recent call last):
  File "notebook", line 4, in suite
TypeError: 'int' object is not iterable
1
  • 2
    You should iterate over range(n) instead Commented Jan 27, 2016 at 18:38

3 Answers 3

4

Your error is here:

for i in n:

n is an integer and not an iterable. Perhaps you wanted to use xrange() (Python 2 only) or range() (recommended on Python 3) here:

for i in range(n):

Note that this starts iteration at 0, not 1 (up to and including n - 1). You could either use range(1, n + 1), or simply add 1 to your sum:

def suite(n):
    total = 0
    for i in range(n):
        total += i + 1
        yield total

This hasn't really got anything to do with generators; wether or not you used yield, trying to loop over a plain int object doesn't work either way.

Sign up to request clarification or add additional context in comments.

Comments

1

Because your function declaration doesn not correspond with for loop. You cannot iterate over integer, you should use some iterable instead. The simplest way is to use range:

The correct version is:

def suite(n):
    total = 0
    for i in range(n):
        total += i
        yield total
>>>suite(6)

Or, you can do another change to yield sum of some iterable:

def suite(iterable):
    total = 0
    for i in iterable:
        total += i
        yield total

>>>suite([1,2,3])

2 Comments

This has little to do with a function declaration. You'd get the same error with that loop outside a function.
See edited answer. I meant that declaration doesn't correspond with for loop.
0

Use range to create an iterator to use in your for loop:

def suite(n):
    total = 0
    for i in range(1, n+1):
        total+=i
        yield total

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.