user2131316
user2131316

Reputation: 3277

why the following range does not print out in python?

I have the following code in python:

def main():
    for i in range(-10, -100):
        print(i, end=' ')

if __name__ == '__main__':
    main()

but it print out nothing, but if i change the main function as:

def main():
    for i in range(-100, -10):
        print(i, end=' ')

it print out the expected result, what is the reason that the first one does not work?

P.S, I found the following example code in python tutorial:

range(-10, -100, -30)
  -10, -40, -70

then why this works, just because it added a step(-30)?

Upvotes: 0

Views: 193

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213243

The default step value for range() function is 1. So, for your range to work, your 1st argument(start) must be smaller than the 2nd argument(end).

If you have the 1st argument(start) larger than 2nd argument(end), you can never reach the end value by adding step of 1 to start. In that case, you can give a step value of -1 to go in opposite direction:

for i in range(-10, -100, -1):

now i will take the value -10, -11, -12, so on, till -99.

Upvotes: 3

Mahmoud Aladdin
Mahmoud Aladdin

Reputation: 546

A small simulation to the function range([start ,] stop [, range]) with positive range (default being 1) is

def range(start, stop, range):
    lst = []
    while start < stop:
       lst += [start]
       start += range
    return lst

so if range(-10, -100) will fail start < stop , thus will print nothing.

However, if you used range(-10, -100, -1), the range is negative thus the simulation will differ by replacing start < stop to start > stop. it will work, however will print the numbers from -10 till -99 the reverse of the second function

Upvotes: 0

Related Questions