user8471763
user8471763

Reputation:

Unable to skip numbers using a for loop

I just want to print some numbers using a basic python for loop:

for i in range(10):
    i = i+1
    print(i)

Expected Output :

1
3
5
7
9

Actual Output :

1
2
3
4
5
6
7
8
9
10

Why doesn't the variable 'i' jump one step when it's i = i+1. What I assume is both i's are different? Because I tried printing the id using print(id(i)). Correct me if I'm wrong.

Upvotes: 1

Views: 715

Answers (5)

Kallz
Kallz

Reputation: 3523

>>> p = range(1,10,2)
>>> p
[1, 3, 5, 7, 9]

or

>>> def test(last,step):
...     for item in range(1,last,step)
...         print item
>>> test(10,2)
1 
3
5
7
9
>>> 
>>> test(15,2)
1 
3
5 
7
9
11
13

Upvotes: 3

Sam51
Sam51

Reputation: 251

Python for loops don't care about any edits made to their temporary variable during the loop. When it reaches the end it ticks whatever iterator you fed it to the next item. i in your case isn't the index of the range you gave it, it's the output of the range, at the loop's inbuilt pointer. Cricket's answer is the nicest way to solve your problem, but if you wanted to alter the loop from within itself, use external variables:

numberlist = range(0,10)
i=0
while i < numberlist[-1]:
    i+=1 #+1 to skip
    print i
    i+=1 #+1 to turn while into for

Upvotes: 1

Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20137

you can try two method, this is in your way,

>>> for i in range(10):
...     if i%2!=0:
...       print i
... 
1
3
5
7
9
>>> 

and the next is, as @colspeed suggested for i in range(1,10,2)

Upvotes: 1

cs95
cs95

Reputation: 402523

The thing to note here is that changing the value of i does not affect the number of iterations. You current code steps from 0 through 9, incrementing one to the current value. It does not skip those iterations. i is just a loop variable that the for loop assigns, it does not control iteration in any way.

Use the range function's step parameter instead:

In [665]: for i in range(1, 10, 2): # start, stop, step
     ...:     print(i)
     ...: 
1
3
5
7
9 

What happens is that range by default steps one at a time, so you'll end up stepping through iterations you wish to skip.

Upvotes: 4

Julien
Julien

Reputation: 15071

When you iterate over the list [0,1,...9] (range(10)), at first iteration, i is set to 0, then no matter what you do with i from there, it won't change the fact that i will be set to 1 at the next iteration, and so on. This is the answer to why it doesn't work as you expect. See other answers for how you can fix it...

Upvotes: 0

Related Questions