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

Here , "i" will be initialized as "1" which lies in [1, 4) , So it should print 1 , but it doesn't print anything. Why ?

1
  • 3
    There are multiple resources online. Try reading the docs for range. Commented Oct 19, 2019 at 6:12

3 Answers 3

2

Here your step value is negative

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

The first value would be 1 + (-1) * 0 = 1, which is less than your step value (4) and this fails the second constraint.

so if you go through the formula, its obvious nothing would get printed - Reference

Sign up to request clarification or add additional context in comments.

Comments

1

In order to make it work you should have: range(4, 1, -1).

As said on the documentation :

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

Comments

0

According to this part of the documentation:

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

Your first value would be 1 + (-1) * 0 = 1, which is less than your stop value of 4. So the second constraint applies, and this value isn't kept. Your range is empty.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.