prap4search
prap4search

Reputation: 5

why for i in range(0,10,-1): wont print anything

for i in range(0,10,-1):
     print (i)

Why the above program prints nothing ,i expect it to print at least 0 According to "for i in range(start, end, iterator)" definition ,it evaluates first element and then uses iterator to get to next element. So in theory the Example code snippet should first take 0 and print it and then next element is evaluated as -1 which is not in 0-10 then it should bail out

Upvotes: 0

Views: 4802

Answers (4)

AvahW
AvahW

Reputation: 2201

In Python, the range function works with the arguments range(StartingValue, EndingValue, Step) the problem you have is that you are assigning a negative step to a situation where the StartingValue is less than EndingValue. Since this is the case, it never enters the loop, because the end value has already been reached, and exceeded.

To fix this, just reverse the first two values: for I in range(10,0,-1) . Think of it as if you were saying it in a sentence, such as FOR each ITEM in the RANGE of 10 to 0 decreasing by 1

Upvotes: 0

mtd
mtd

Reputation: 2364

There is no evaluation of the first element by the range() call, and Python's range() function will not return anything if step is negative and start + i * step is not greater than stop. For your example, start = 0 + 0 * -1 is not greater than stop = 10, so your range call returns the empty list, and your for loop has nothing to iterate over.

$ python -c 'print(range(0,10,-1))'
[]

range()'s documentation:

range(stop)

range(start, stop[, step])

This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:

Upvotes: 2

Neel
Neel

Reputation: 21243

Third argument in range is step

In range you can give step as 1, 2 etc.

When you give -1, it will not do step in reverse.

If you want to print reverse order you can try

>>> range(10)[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Upvotes: 0

mgilson
mgilson

Reputation: 309929

With a negative "step", python keeps on yielding1 elements while the current value is greater than end. In this case, you start at 0. 0 is not greater than or equal to 10 so python's done and nothing gets yielded.


1This is a simplification of course -- range returns a range object on python3.x which is an indexable sequence type so it doesn't exactly yield, but the basic idea is the same ...

Upvotes: 2

Related Questions