Why do we use a for loop

Python course

Previous chapter: while loop
Next chapter: output with print

for loops

For loop syntax

for variable in sequence: statement1 statement2 ... statementn else: Else statement1 Else statement2 ... Else statementm The for statement has a different character to the for loops known from most other programming languages. In Python, the for loop is used to iterate over a sequence of objects, while in other languages ​​it is mostly just "a slightly different while loop".
Example of a for loop in Python: >>> languages ​​= ["C", "C ++", "Perl", "Python"] >>> for x in languages: ... print x ... C C ++ Perl Python >>>

The range () function

With the help of the range () function, the for loop can be ideally used for iterations. range () returns lists that correspond to arithmetic enumerations.
Example:

>>> range (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The above example shows that Range, called with one argument, returns the list of numbers from 0 to this argument.
range () can also be called with two arguments: range (begin, end) Then a list of all integers from begin (including) to end (exclusively) is returned.
As a third argument, range () can also be given the step size.
Example:
>>> range (4,10) [4, 5, 6, 7, 8, 9] >>> range (4,50,5) [4, 9, 14, 19, 24, 29, 34, 39, 44, 49] The range () function is particularly useful in conjunction with the for loop. In the following example we form the sum of the numbers from 1 to 100: n = 100 s = 0 for i in range (1, n + 1): s = s + i print s
There is still a terrible efficiency problem hidden in the small program above. What happens before the for loop is executed? Python first evaluates the range (1, n + 1) call. This means that a list with 100 numbers is generated, ie [1, 2, 3, 4, ... 100]. All of the numbers in this list are required within the loop, but not the entire list at any point in time. In the previous chapter we solved this problem with a while loop and we didn't need a list there either. Python offers a solution to this problem by providing the xrange function. xrange creates an iterable object, which means that no list is created but, for example, the values ​​can be iterated over in a for loop without the list being created: >>> for i in xrange (1, 7) : ... print (i) ... 1 2 3 4 5 6 >>> In terms of efficiency, the above loop behaves similarly to the following while loop: >>> i = 1 >>> while i < 7:="" ...="" print(i)="" ...="" i="" +="1" ...="" 1="" 2="" 3="" 4="" 5="" 6="">>> Of course, there is no difference in the output behavior. You can see the difference between range and xrange if you make the calls directly in the interactive Python shell: >>> range (1,7) [1, 2, 3, 4, 5, 6] >>> xrange ( 1,7) xrange (1, 7) >>>

Example: Calculating the Pythagorean Numbers

Most believe that the Pythagorean Theorem was discovered by Pythagoras. Why else should the sentence get its name? But there is a debate as to whether this theorem could not also have been discovered independently of Pyhtagoras and, above all, earlier. For the Pythagoreans - a mystical movement based on mathematics, religion, and philosophy - the integers that filled the Pythagorean theorem were special numbers that were sacred to them.

There is nothing mystical about Pythagorean numbers these days. Though they may still seem that way to some students or other people at war with math.
In mathematics, the following applies quite unromantically:
Three natural numbers that satisfy the equation a2+ b2= c2 meet are called Pythagorean numbers.
The following program calculates all Pythagorean numbers up to a maximum number to be entered: #! / Usr / bin / env python from math import sqrt n = raw_input ("Maximum number?") N = int (n) +1 for a in xrange ( 1, n): for b in xrange (a, n): c_square = a ** 2 + b ** 2 c = int (sqrt (c_square)) if ((c_square - c ** 2) == 0): print a, b, c

Iteration over list with range ()

If you want to access the indexes of a list, it doesn't seem like a good idea to use a for loop to iterate over the list. You can then reach all elements, but the index of an element is not available. But there is a way to access both the index and the element. The solution is to use range () in combination with the len () function, which returns the number of elements in the list: fibonacci = [0,1,1,2,3,5,8,13,21] for i in xrange (len (fibonacci)): print i, fibonacci [i] print

List iteration with side effects

If you are iterating over a list, you should avoid changing the list in the loop body. We show what can happen in the following example: colors = ["red"] for i in colors: if i == "red": colors + = ["black"] if i == "black": colors + = [ "white"] print colors What does the "print colors" instruction output? ['red', 'black', 'white'] It is best to use a copy of the list, as in the next example: colors = ["red"] for i in colors [:]: if i == "red": colors + = ["black"] if i == "black": colors + = ["white"] print colors The output now looks like this: ['red', 'black'] We have also changed the list now , but "consciously" within the loop body. But the elements that are interated via the for loop remain unchanged through the iterations.

Previous chapter: while loop
Next chapter: output with print