In python, for and while are looping statements.
Looping statements help to execute the specific blocks of code repeatedly.
Python for statement iterates over the items of any sequence (a list, tuple, set, dictionary, string) in the order by which they appear.
numbers_list = [
0, 1, 2, 3, 4, 5
]
for number in numbers_list:
print(number)
0
1
2
3
4
5
In the above example, we declared a list of elements from 0
to 5
and assigned that list to the numbers_list
variable. Using the for
loop statement, we iterate that list and print the numbers.
The break
keyword helps to stop the iteration of looping statements.
numbers_list = [
0, 1, 2, 3, 4, 5
]
for number in numbers_list:
if number == 3:
break
print(number)
0
1
2
In the above example, we used a for loop to print the numbers 0
to 5
. However, if the number
equals 3
(number == 3
), then after we break
the for loop iteration since the number only prints from 0
to 2
, and then it stops.
The continue
keyword allows us to stop the current iteration of the loop and continue with the next.
numbers_list = [
0, 1, 2, 3, 4, 5
]
for number in numbers_list:
if number == 3:
continue
print(number)
0
1
2
4
5
In the above example, we used a for loop to print the numbers 0
to 5
. However, if the number
equals 3
(number == 3
), call the continue
keyword because calling the continue
will skip the current iteration and move to the next. In the output, you see the numbers 0
to 5
are displayed, but the number 3
is missing.
After for loop iteration is complete, then else
block statements will execute.
numbers_list = [
0, 1, 2, 3, 4, 5
]
for number in numbers_list:
print(number)
else:
print("For loop iteration complete.")
0
1
2
3
4
5
For loop iteration complete.
In the above example, we used a for loop to print the numbers 0
to 5
. After the for
loop iteration completes, it executes an else
block and prints the statement "For loop iteration complete.".
Using the break
keyword for loop iteration stops, and in this case, the else
block will not execute.
numbers_list = [
0, 1, 2, 3, 4, 5
]
for number in numbers_list:
if number == 3:
break
print(number)
else:
print("For loop iteration complete.")
0
1
2
As you can see, we added a condition if the number
equals 3
(number == 3
), then break
the for loop iteration. In this case, the numbers only print from 0
to 2
.