for loops

We've seen for loops in previous examples; they are the go-to sequence iterator for Python. The for loops work on nearly anything: strings, lists, tuples, and so on. The main format is shown next. Note how for loops have the same basic look as while loops:

for <target> in <object>:  # assign object items to target 
    <statements> 
    if <test>: 
        break  # exit loop now, skip else 
    if <test>: 
        continue  # go to top of loop now 
    else: 
        <statements>  # if we didn't hit a 'break'

When the for loop starts, it looks at the first item in the sequence. This item is given a value of 0 (many programming languages start counting at 0, rather than 1). Once the code block has finished doing its processing, the for loop looks at the second value and gives it a value of 1. Again, the code block does its processing and the for loop looks at the next value and gives it a value of 2. This sequence continues until there are no more values in the list. At that point, the for loop stops and the control proceeds to the next operation in the program. Following screenshot shows how nested for loops are:

for loop

The first loop increments a counter from 2 through 20, while the second loop increments from 2 through the current count. If the remainder of i divided by x is 0, the inner loop breaks and returns to the outer loop.

The % symbol is the modulus operation, which returns the remainder of a division operation. The range() function automatically generates a list of integers, in memory, starting from the first number provided (inclusive) and stopping at the second number provided (exclusive). A third number can be provided that indicates how many numbers to skip between each integer generated.

Strings and tuples can also be a good location to use a for loop. Iteration through the items in a string or tuple is easily accomplished with a loop, and is frequently used for processing text. Following screenshot demonstrates the sequence iteration:

for loops with sequences

A string and a tuple are defined in lines 35 and 36, respectively. In line 37, the for loop iterates over, and prints out the string, character by character. In line 38, a similar thing occurs with the tuple, except we have told the print() function to add a comma to the end of each number printed. Note that a comma is included after the final number due to this feature.

Because for loops are pretty simple and tend to run more quickly than while loops, they are the preferred loop when iterating through a sequence. In general, avoid counting things in Python, since the built-in iteration tools can do much of the work you would have to manually write.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset