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 good old i++ .

JavaScript example:

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

I have some questions regarding this iteration:

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

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

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

Answer:

The for Python is actually a for each . There is for traditional with three elements where you place the start, end and step "increment". But if you think about it this one is traditional it's 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"

Decrease:

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 to 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 needs to be taken.

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

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

Decreasing:

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

See working on ideone . And on repl.it. Also posted 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