Hi!
I'm new at python and I don't get the while statement. I'm trying to make a simple function that returns each term of a geometric progression 'til 'n'.

def gp(a1,r,n):
    while not n == 0:
        n = n - 1
        an = a1 * (r ** n)
        return an

For gp(3,3,3)
It should return:

27
9
3

But it returns

27

It always returns the last (n=n-1) term of the GP.

Adding a print statement should help. If you want to store more than one value, a list is usually the container of choice.

def gp(a1,r,n):
    ## can also be done with list comprehension
    print [ a1 * (r ** x) for x in range(n)]

    while n > 0:
        n = n - 1   ## if 'n' was 1 it is now zero
        an = a1 * (r ** n)
        print n, "returning", an
        return an

In your code, you have a kind of double negative here:

while not n == 0:

This is saying that "while 'n' does not equal 0", do stuff.
A simpler way of writing this is "while n != 0:".
The "not" is only really used for boolean. ie:

a = True
while not a:
	print ':)'

the "not" effectively means "false". So: "while 'a' is false".

In your code, you have a kind of double negative here:

while not n == 0:

This is saying that "while 'n' does not equal 0", do stuff.
A simpler way of writing this is "while n != 0:".
The "not" is only really used for boolean. ie:

It looks rather like you are going to use the first bit :)

Just a note: a more convential way of doing this starts at zero and counts to 'n', not the other way round. It won't make any difference, it's just a convention.

Line 3 could also be:

n -= 1

Thanks woooee that's a really clever solution.

Thank you SgtMe for the tips they're very usufull.

Thanks woooee that's a really clever solution.

Thank you SgtMe for the tips they're very usufull.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.