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
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
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)
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)
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.
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