user3234828
user3234828

Reputation: 59

Python: how to return all results in a loop?

def pop(n):
    result,counter = 0,0
    while counter<=n:
        result=(2**counter)
        counter=counter+1
    return result

example:
>>>pop(4)
16

How do i return all the results? like:

1
2
4
8
16

Upvotes: 0

Views: 1960

Answers (2)

Peter
Peter

Reputation: 103

The pythonic way would be something like this:

def pop(n): return [2**x for x in range(n)]

Upvotes: 1

arocks
arocks

Reputation: 2882

You can store the result in an list:

def pop(n):
    result,counter = [],0
    while counter<=n:
        result.append(2**counter)
        counter=counter+1
    return result

Now the result will be a list of all powers.

Alternatively, you can create a generator to yield multiple results

def pop(n):
    result,counter = 0,0
    while counter<=n:
        yield 2**counter
        counter=counter+1

Now if you do a list(pop(4)), then you will get a list of all results

Upvotes: 4

Related Questions