Python For Loop
Python For Loop
For example, if we want to show a message 100 times, then we can use a loop. It's just a simple
example; you can achieve much more with loops.
There are 2 types of loops in Python:
for loop
while loop
In Python, a for loop is used to iterate over sequences such as lists, tuples, string, etc. For
example,
languages = ['Swift', 'Python', 'Go', 'JavaScript']
output:
Swift
Python
Go
JavaScript
Here, val accesses each item of sequence on each iteration. The loop continues until we reach the
last item in the sequence.
Output:
P
y
t
h
o
n
# iterate from i = 0 to i = 3
for x in values:
print(x)
Output:
1
2
3
4
It is not mandatory to use items of a sequence within a for loop. For example
languages = ['Swift', 'Python', 'Go']
Here, the loop runs three times because our list has three items. In each iteration, the loop body
prints 'Hello' and 'Hi'. The items of the list are not used within the loop.
If we do not intend to use items of a sequence within the loop, we can write the loop like this:
for _ in languages:
print('Hello')
print('Hi')
The _ symbol is used to denote that the elements of a sequence will not be used within the loop
body.
A for loop can have an optional else block. The else part is executed when the loop is exhausted
(after the loop iterates through every item of a sequence). For example,
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Output
0
1
5
No items left.
The break Statement
With the break statement we can stop the loop before it has looped through all the items:
Example
Output:
apple
banana
Example
Exit the loop when x is "banana", but this time the break comes before the print:
Output:
apple
The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with the
next:
Example
output:
apple
cherry
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.
Example
for x in range(6):
print(x)
output:
0
1
2
3
4
5
The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
Example
The range() function defaults to increment the sequence by 1, however it is possible to specify
the increment value by adding a third parameter: range(2, 30, 3):
Example
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
output:
0
1
2
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
for x in adj:
for y in fruits:
print(x, y)
The pass Statement
for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
while loops
for loops
With the while loop we can execute a set of statements as long as a condition is true.
Example
i=1
while i < 6:
print(i) #1 2 3 4 5
i += 1 #i=i+1
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.
With the break statement we can stop the loop even if the while condition is true:
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
i=0
while i < 6:
i += 1 #1 #2 #3 #4 #5 #6
if i == 3:
continue
print(i)
i=1
while i<6:
if i==3:
continue
print(i)
i+=1
output:
1
2
4
5
The else Statement
With the else statement we can run a block of code once when the condition no longer is true:
Example
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")