Skip to content Skip to sidebar Skip to footer

Using "yield" In A Function

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 m

Solution 1:

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 =0for 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.

Solution 2:

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 =0for 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 = 0for i in iterable:
        total += i
        yield total

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

Solution 3:

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

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

Post a Comment for "Using "yield" In A Function"