Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for i in range(start,stop,step) Python 3

I want to list a range of numbers and I'm using the "for i in range(start,stop,step)".

def range():
    P=36
    for i in range(P+1,0,-1):
        P=P-4
        print(P)

I want to list the numbers down to 0 but it goes all the way to -112.

I found that if I do this though:

def test():
    P=36
    for i in range(P+1,28, -1):
        P=P-4
        print(P)

It would now stop at 0. Could someone please explain why it does this and doesn't actually STOP at 0? Sorry, I'm new to this and I'm super confused. I would also like the results listed to be able to be referred to afterwards, like stringing the results together to form a line with a polygon but can't simply write

list(P)

instead of print(P)

like image 877
Mason Avatar asked Feb 07 '23 04:02

Mason


1 Answers

To create a list from 36 to 0 counting down in steps of 4, you simply use the built-in range function directly:

l = list(range(36,-1,-4)) 
# result: [36, 32, 28, 24, 20, 16, 12, 8, 4, 0]

The stop value is -1 because the loop runs from the start value (inclusive) to the stop value (exclusive). If we used 0 as stop value, the last list item would be 4.

Or if you prefer a for loop, e.g. because you want to print the variable inside it:

for P in range(36,-1,-4):
    print(P)
like image 137
Byte Commander Avatar answered Feb 12 '23 11:02

Byte Commander