-2

Here is my code?

for i in range (10,20,2):
    print(i)

The output should be like this

10
12
14
16
18
20

But output is coming:

10
12
14
16
18

Why 20 is not coming?

Jaskaran singh Rajal
  • 2,270
  • 2
  • 17
  • 29
  • You need to replace 20 with 22 – Mazdak Jan 06 '15 at 16:03
  • This answer should help with the intuition: http://stackoverflow.com/a/4504677/3019689 – jez Jan 06 '15 at 16:07
  • Did it ever occur to you to [RTFM](https://docs.python.org/2/library/functions.html#range)? *"If `step` is positive, the last element is the largest `start + i * step` **less than `stop`**"* (emphasis mine). It is even more explicit in [the tutorial](https://docs.python.org/2/tutorial/controlflow.html#the-range-function): *"The given end point is never part of the generated list"*. – jonrsharpe Jan 06 '15 at 16:18

3 Answers3

1

The second argument to range is exclusive (not included). You would need to set stop equal to 22:

for i in range(10,22,2):
    print(i)

to have 20 be in the output:

>>> for i in range(10,22,2):
...     print(i)
...
10
12
14
16
18
20
>>>
0

The range function always prints upto the max val

for i in range (10,22,2):
    print(i)

This will print as expected

10
12
14
16
18
20
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
-1

The maximum value is not included. If you want 20 to appear, you'll need 20+1 as max value.

Marc Plano-Lesay
  • 6,808
  • 10
  • 44
  • 75