For for incrementing in Python

Question:

I learned that in Python , to loop with for , from 1 to 10, we use range .

Like this:

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

Generally, in other languages, when we need to do a simple increment, we use the good old i++ .

JavaScript example:

for (var i; i < 10; i++){
    console.log(i);
}

I have some doubts regarding this iteration:

  1. How would I do it to decrement instead of incrementing?

  2. How would I increment this loop by two by two values, starting from 1 ?

  3. Is there any way to loop , as is often done in other languages ​​such as i++ ?

Answer:

Python's for is actually a for each . There for no traditional three-element for where you put the start, end, and "increment" step. But if you think about it this is traditional is just syntax sugar . A while does the same thing.

i = 1 #inicializador
while i < 10: #verifica a condição
    print(i) #o corpo, a ação
    i += 2 #o passo de "incremento"

Decrement:

i = 10 #inicializador
while i > 0: #verifica a condição
    print(i) #o corpo, a ação
    i -= 1 #o passo de "incremento"

It's that simple.

There is a difference in using a continue since normally in a traditional for a continue will not skip the "increment" step, in this while construction it will skip, so more care is needed.

But this is not the most "pythonic" way. Using range is always recommended as shown in Orion's answer. See the increment of 2:

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

Decrementing:

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

See it working on ideone . And on repl.it. I also put it on GitHub for future reference .

Intuitively the while should be faster but as the range is written at a lower level it manages to produce more optimized code.

Scroll to Top