Home > Enterprise >  Range function with step higher than stop
Range function with step higher than stop

Time:04-10

Could someone explain me why the output is 22 here:

def fun():
    for x in range(22,23,24):
        print(x)
fun()

CodePudding user response:

The syntax for range is range(start, stop, step)

The range of numbers to be printed starts from 22, to 23 (end point not included), in steps of 24.

The first number is 22, which gets printed.

The next number will be 22 24 = 46, which is greater than 23, so it doesn’t get printed and the loop terminates.

CodePudding user response:

You are iterating over a range which starts with 22, ends before 23, and makes steps of 24.


To better understand what you are doing, try this:

>>> list(range(22,23,24))
[22]

You are starting from 22, then doing a step of 24, and you clearly exceeded the limit of 23 since you are at 46 with 22 24.


I would suggest to read the documentation about range's constructor.

range(start, stop[, step]) # This is the prototype of the constructor
  • Related