Python Loops - Learn How to Use for and while Loops in Python
Loops are an essential feature of any programming or scripting language. Having the ability to execute a task multiple times is fundamental to any language.
In Python, looping is achieved via the use of for
and while
loops and in this article we look at how to use them with examples.
Python for Loop
The for
loop in python can be used in various ways. One simple and most common way it to iterate over a collection.
Syntax
for i in collection:
statement
The collection can be a list, set, range, etc. i is a variable that takes the value of the element that is being iterated.
my_list = [1, 2, 3, 4, 5]
for i in my_list:
print("Value is:", i)
Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
You can see how the list is iterated from the start to the end.
for Loop With range()
The range method in python is used to create a sequence ranging between a certain limit. Suppose you don’t have a list but you want to loop over something a specified number of times. You can use the range()
method.
for i in range(5):
print(i)
Output:
0
1
2
3
4
The range()
function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at the specified number.
If we wanted to have a different starting value and a different increment value, we use:
for i in range(10, 30, 5):
print(x)
Output:
10
15
20
25
In the above example, we start from 10, we terminate at 25 and we increment by 5.
for Loop With else
The else
keyword in a for
loop specifies a block of code to be executed after the loop is finished.
for i in range(6):
print(i)
else:
print("Finished looping.")
Output:
0
1
2
3
4
5
Finished looping.
if
statement, else block executes only when the condition is false, but in the for
loop, the else
block is always executed.
Nested for Loops
We can have a for
loop inside another for
loop. This is called a nested loop.
The “inner loop” will be executed one time for each iteration of the “outer loop”.
Example:
numbers = [1, 2, 3]
chars = ["a", "b", "c"]
for i in numbers:
for y in chars:
print(x, y)
Output:
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
Python While loop
The while
loop executes a set of statements as long as a condition is true.
For example:
i = 1
while i < 5:
print("Hello world")
i = i + 1
While loop with else
The else statement within the while
loop executes once when the condition is no longer true.
For example:
i = 1
while i < 5:
print("Hello world")
i = i + 1
else:
print("The execution has ended")
Output:
Hello world
Hello world
Hello world
Hello world
The execution has ended
Using break in while Loop
The break statement is used if you want to break the execution of a loop at a certain point.
In the following example, we want to stop the loop when we encounter the “c” character:
my_list = ['a', 'b', 'c', 'd', 'e']
for i in my_list:
print(i)
if i == 'c':
print("'c' encountered. Breaking the loop")
break
Output:
a
b
c
'c' encountered. Breaking the loop
Using continue in while Loop
The continue keyword is used to skip a statement and continue with the rest of the loop for a particular iteration.
In the example below, we want to continue with the loop when we encounter “c”:
my_list = ['a', 'b', 'c', 'd', 'e']
for i in my_list:
if i == 'c':
continue
print(i)
Output:
a
b
d
e
Note that “c” is not printed. The loop continues to print “d” and “e”.
Summary
- The
for
andwhile
loops are used for iteration - They are used to execute a set of statements multiple times or to iterate over a collection such as a list
- The
for
loop in python can also be used with therange()
method. You can either provide both lower and upper limits or only upper limit. In the latter case, 0 will be assumed as the lower limit - Use the
for
loop when you know how many times the loop should execute - The
while
loop has a condition and it runs until the condition is false - The
while
loop should always have a mechanism to break the condition or the loop will run forever - Use the while loop when you do not know many times the loop should execute
- The
else
block can be used with both thefor
andwhile
loop. It is always executed. - The
break
keyword is used to terminate the execution. No further iteration will be done if the break keyword is encountered. - The
continue
keyword skips the current iteration and jumps directly to the next iteration.