Python – Iteration/Looping
Loops are used to control the repeated execution of selected statements in Python. As other programming languages, Python also have While and For loops.
Two Types of Loops in Python
1. While Loop
While loop is used to iterate one or more code statements as long as the test condition or expression is True. This iteration is usually used when the number of times we need to repeat the block of code to execute is not known.
The Python while loop has the basic form:
while <test-condition-is-true>: statement or statements
Rules:
- Evaluating test-condition will be performed before the first iteration of the code, therefore if the condition fails – the statement of code inside the while loop will not be executed even once
- Like if statement, indentation is key here as the statements included in the while statement are determined by indentation. Each statement that is indented to the same level after the while condition is part of the while loop.
For example,
count = 0 print('Starting') while count < 10: print(count, ' ', end='') # part of the while loop count += 1 # also part of the while loop print() # not part of the while loop print('Done')
Above code snippet will produce an output as below,
Starting 0 1 2 3 4 5 6 7 8 9 Done
2. For loop
Although the while loop can be used for iterations, the for loop is more concise way to do iteration as well. The for loop is used to step a variable through a series of values until a given test is met. The behavior of the for loop is illustrated in below.
The format of for-loop in Python uses range of values as below,
for <variable-name> in range(...): statement statement
Range is actually a function that will generate the range of values to be used as the sequence in the for loop. This is because the Python for
loop is very flexible and can loop over not only a range of integer value or data structures such as a list of integers or strings.
For example:
#Loop over a set of values in a range print('Print out values in a range') for i in range(0, 10): print(i, ' ', end='') print() print('Done')
Above code snippet will produce an output as below,
Print out values in a range 0 1 2 3 4 5 6 7 8 9 Done
Advantage of for-loop over while-loop:
- We are processing a range of values from 0 to 9 as we are clear over the iteration limit
- We did not need to define the loop variable first.
Break Loop Statement
Python allows programmers to decide whether they want to break out of a loop early or not (whether we are using a for loop or a while loop). This is done using the break statement.
The break statement, when executed, will terminate the current loop and jump the program to the first line after the loop. For example,
print('Only print code if all iterations completed') num = int(input('Enter a number to check for: ')) for i in range(0, 6): if i == num: break print(i, ' ', end='') print('Done')
If user inputs 8, above code snippet will give output as below,
Enter a number to check for: 8 0 1 2 3 4 5 Done
However, if we enter the value 3 then only the values 0, 1 and 2 will be printed as below,
Enter a number to check for: 3 0 1 2 Done
Continue Loop Statement
Continue statement does not terminate the whole loop; rather it only terminates the current iteration round the loop. This allows you to skip over part of a loop’s iteration for a particular value, but then to continue with the remaining values in the sequence. For example,
for i in range(0, 10): if i % 2 == 1: continue print(i, ' ', end='') print('its an even number') print('Done')
When above snippet is executed, it will terminate the loop for all odd numbers and print output as below,
0 its an even number 2 its an even number 4 its an even number 6 its an even number 8 its an even number Done
For Loop with Else
A for loop can have an optional else block at the end of the loop. The else part is executed if and only if all items in the sequence are processed. For example,
# Only print code if all iterations completed over a list print('Only print code if all iterations completed') num = int(input('Enter a number to check for: ')) for i in range(0, 6): if i == num: break print(i, ' ', end='') else: print() print('All iterations successful')
Above code snippet will produce an output as below when user input 6 or above as all the sequence in the for-loop have been completed,
Only print code if all iterations completed Enter a number to check for: 6 0 1 2 3 4 5 All iterations successful
Conclusion
In this article, we saw about different types of loops in Python. And use of continue, break statement in the iteration.