I am trying to find a way to control the amount my variable 'i' increments by so I decided to include the code 'i = i + 1' within the for loop. My idea was that as my loop would run, it would print the 'i' values '1, 3, 5, 7'. However, when I ran the code, it printed out (1, 2, 3, 4, 5, 6, 7). I am confused as to why this is happening.

for i in range (0, 7):
i = i + 1
print i

Recommended Answers

All 6 Replies

When you use the range function each iteration of the loop sets the value of i back to what the next step in range is. Luckily for you, you can specify how many numbers you want range() to skip on each pass by setting the step

for i in range(0,30,5]
   print i
# prints 0,5,10,15,20,25

To do what you want, use this

for i in range(1,9,2):
    print i

What if I want to control how much my loop will increment by? For example:

for i in range (1, 30)
   if (apple == fruit)
        i = i + 6
   elif (grape == fruit)
        i = i + 2

Is there another way of doing this?

When you use the range function each iteration of the loop sets the value of i back to what the next step in range is. Luckily for you, you can specify how many numbers you want range() to skip on each pass by setting the step

for i in range(0,30,5]
   print i
# prints 0,5,10,15,20,25

To do what you want, use this

for i in range(1,9,2):
    print i

This loop will increment by 2!

for f in range(start=0, end=10, step=2):
    print f

Just replace 2 with anything you need

What if I want to vary my step depending on certain conditions in my loop? For example:

for f in range(start=0, end=10, step=2):
     if (varGrape == varFruit):
             print varGrape
             step = 5
    else:
             print f

This loop will increment by 2!

for f in range(start=0, end=10, step=2):
    print f

Just replace 2 with anything you need

What if I want to control how much my loop will increment by? For example:

for i in range (1, 30)
   if (apple == fruit)
        i = i + 6
   elif (grape == fruit)
        i = i + 2

Use a while loop with a variable defined outside the loop.

ctr = 0
while ctr < 30:
   if (apple == fruit)
        ctr += 6
   elif (grape == fruit)
        ctr += 2
   else ctr += 1   ## prevent endless loop

silly me. of course. a while loop. blah ! *bangs head*

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.