0
print ('Hello')

for i in range(2,11,-2):
    print(i)

Whats wrong with this code? I'm trying to print out :

Hello
10
8
6
4
2

but it only prints out hello. I ctrl+enter twice after print hello

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
tytds
  • 61
  • 1
  • 2
  • 4
    [`range(10, 1, -2)`](https://docs.python.org/3/library/functions.html#func-range) – Stephen Rauch May 06 '18 at 22:26
  • 3
    Possible duplicate of [How to loop backwards in python?](https://stackoverflow.com/questions/3476732/how-to-loop-backwards-in-python) – Stephen Rauch May 06 '18 at 22:28
  • 1
    You are trying to loop from 2 to 11 _in steps of -2_ which actually means backwards and in steps of 2. As it is not possible, it prints nothing. The initial end final values must be corrected – OriolAbril May 06 '18 at 22:32
  • Consider `test = [1,2,3]`. If I slice `test[100:]` I get an empty list, not an error, even though the start value overflowed the range. Its the same thing for, say, `range(100,3)` - since you've already gone over the top in the first step, it just stops iteration. Finally to `range(2, 11, -2)`. Its going backwards, 11 is already "behind" what you can get going backwards, so it stops. – tdelaney May 06 '18 at 22:32
  • @StephenRauch - I didn't see the duplicate there. It shows negative steps to go backwards but doesn't explain why this range test stops without producing anything. – tdelaney May 06 '18 at 22:33

4 Answers4

3

If you specify a negative step in range you also have to make start bigger than stop:

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

Another way to do what you want, would be to use reversed:

for i in reversed(range(2,11,2)):
    print(i)
MegaIng
  • 7,361
  • 1
  • 22
  • 35
2

The range() function will include the first value and exclude the second.

a = " ".join(str(i) for i in range(10, 0, -2))
print (a)
hamma
  • 19
  • 4
  • But what makes this work is the reversal of the start and stop conditions, not the join, or the inclusion / exclusion rules. – tdelaney May 06 '18 at 22:34
2

Read what range() does. First argument is a starting number, you can't start from smaller if you want to print from bigger to smaller.

You can do range(2, 11, 2) for increasingly list or range(10, 1, -2) for decreasingly.

There's also reverse range(2, 11, 2)[::-1] option, but its better to just use it as planned.

OriolAbril
  • 7,315
  • 4
  • 29
  • 40
DecaK
  • 286
  • 2
  • 13
1

Since your range starts at 2, and ends at 11, this code won't work since you are stepping down by -2. You will have to START at 10 and then step down negatively instead of stepping down from 2. Below I have an example that gets you the output that you are seeking:

print('Hello')

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

And here is your output:

Hello
10
8
6
4
2
Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27