For for incrementing in Python

8

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

More or less 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 about this iteration:

  • How would I do to instead of incrementing I decrement?

  • ?

  • Is there any way to loop , as is usually done in other languages, such as i++ ?

  • asked by anonymous 13.02.2015 / 16:03

    3 answers

    9

    The for f% of Python in the background is for each . There is no traditional% with three elements where you put the beginning, end and step of "increment". But if you think about it this is traditional syntax sugar . A for does the same thing.

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

    Define:

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

    It's that simple.

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

    But this is not the most "pythonic" way. The use of continue is always recommended as Orion's response shows. See the increase of 2:

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

    Decreasing:

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

    Intuitively, while should be faster but since range is written at a lower level it can produce more optimized code.

        
    13.02.2015 / 16:19
    8

    To decrease:

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

    To increment two by two:

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

    In order to do i++ , there is no way, you would have to use contador+=1

        
    13.02.2015 / 16:20
    3

    As people put it in the other answers, what happens is that the for in the languages that inherit the C syntax is only an while incremented.

    In Python it is rare to actually use numeric%% in an application - because in the vast majority of cases, in%% of what we want is to perform a set of operations for each element of a sequence. The sequence can be elements of a vector, lines of a file, records retrieved from a database, letters from a string ... In other languages, people usually make a for with the variable going from 0 to the length of the sequence, and one of the first commands within for makes an assignment of type for . In Python, the for that exists since the language was created in the 90's is what is sometimes called item = sequencia[i] in other languages (but not in Javascript, there the for each is not very consistent).

    In cases where we really want to count numbers, in Python there is the call for which returns a very flexible object for integer counting, being trivial to pass parameters to decreasing counts or 2 counts. is asking, it is best to make it clear. For 10 to 1, decreasing: for each : the 10 is the initial parameter, 0, the final: when the value is the interaction for, and -1 the increment. Likewise, by 2 in 2:% with% here the count starts at 0, and increases by 2 by 2, and by when the value is 10 or greater.

    More often than not, we need an item from a sequence and its index number at the same time. For example, if we want to compare each letter of a string with the next one, to see if they are the same:

    palavra = input("Digite uma palavra: ")
    total_repetidas = 0
    for i, letra in enumerate(palavra):
       if i < len(palavra) - 1 and letra == palavra[i + 1]:
           total_repetidas += 1
    print(f"Há um total de {total_repetidas} letras iguais em sequência em {palavra}")
    

    Here, the so-called "enumerate" will return, for each element in the sequence contained in range a tuple with two elements: the first being the position of the next element, and the second the element itself. Another feature of Python allows you to place two variables separated by for i in range(10, 0, -1) in for i in range(1, 10, 2): , and the content of the tuple is associated, respectively each item to a variable.

    Now that's not even cool. The cool thing is that it's easy to create your own calls that can be used in palavra , just like , and for . It is enough that the function has the expression for inside: the yield works as if it were a range partial: the function returns a value, that can be used in enumerate (or in other ways); when it is executed again, the function keeps running from where it was - and in the next yield it creates the next value. this type of function becomes a "generating function".

    With this, sometimes code that is not the purpose of our main application can be written in a separate place - it can be tested independently. Let's suppose I want to make a return that generates the squares of the numbers instead of a linear increment:

    def quadrados(n):
       for i in range(n):
          yield n * n
    

    Ready - that's all. If I now want to print all squares of numbers from 0 to 100 I can do:

    for i in quadrados(100):
        print(i)
    

    (as in calling normal functions, the variables within for are isolated - so I can re-use the yield variable without any danger).

    If I want a function that returns the fibonacci series until the value of the series exceeds a number x:

    def fibonacci(max_):
       a = 1
       b = 1
       while a < max_:
          yield a
          c = b
          b += a
          a = c
    

    (Again, with the history of assigning multiple variables using a "," in Python it is possible to rewrite the last three lines like this:

    b, a = b + a, b
    

    How this works: First, Python executes the expression on the right side. Since it has a "," it will create a tuple. Then it executes the expression in the first element of the tuple for and the second element - and these are the values of the temporary tuple: (a + b, b). Then the first element of this tuple goes to variable "b" and the second element to variable "a")

        
    12.02.2018 / 20:13