8.2 Python For Loop
8.2 Python For Loop
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is
assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item
in the list is assigned to iterating_var, and the statements block is executed until the entire
sequence is exhausted.
Flow Diagram
Example
#!/usr/bin/python
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
#!/usr/bin/python
Here, we took the assistance of the len built-in function, which provides the total number of
elements in the tuple as well as the range built-in function to give us the actual sequence to iterate
over.
If the else statement is used with a for loop, the else statement is executed when the loop
has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.
The following example illustrates the combination of an else statement with a for statement that
searches for prime numbers from 10 through 20.
#!/usr/bin/python
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number
Loading [MathJax]/jax/output/HTML-CSS/jax.js