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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With