In python, for and while are looping statements.
Looping statements help to execute the specific blocks of code repeatedly.
While loop executes a block of statements repeatedly until a given condition is satisfied.
number = 0
while number < 5:
number = number + 1
print(number)
print("While loop execution completed.")
1
2
3
4
5
While loop execution completed.
In the example, we declared a number
variable and assigned a 0
value. After that, we set a while loop with the condition that a number
is less than 5
(number < 5
), then increment and print the number value with each iteration(number = number + 1
). The while loop iterates until a condition is True, and if a condition is False, it stops its iteration. When the Python while loop iteration is complete, print the text "While loop execution completed.".
The break
keyword helps to stop the iteration of looping statements.
number = 0
while number < 5:
number = number + 1
if number == 3:
break
print(number)
1
2
In the above example, we used a while loop to print the numbers 1
to 5
. However, if the number
equals 3
(number == 3
), then after we break
the while loop iteration since the number only prints from 1
to 2
, and then it stops.
The continue
keyword allows us to stop the current iteration of the loop and continue with the next.
number = 0
while number < 5:
number = number + 1
if number == 3:
continue
print(number)
1
2
4
5
In the above example, we used a while loop to print the numbers 1
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 1
to 5
are displayed, but the number 3
is missing.
After while loop iteration is complete, then else
block statements will execute.
number = 0
while number < 5:
number = number + 1
print(number)
else:
print("While loop iteration complete.")
1
2
3
4
5
While loop iteration complete.
In the above example, we used a while loop to print the numbers 1
to 5
. After the while
loop iteration completes, it executes an else
block and prints the statement "While loop iteration complete.".
Using the break
keyword while loop iteration stops, and in this case, the else
block will not execute.
number = 0
while number < 5:
number = number + 1
if number == 3:
break
print(number)
else:
print("While loop iteration complete.")
1
2
As you can see, we added a condition if the number
equals 3
(number == 3
), then break
the while loop iteration. In this case, the numbers only print from 1
to 2
.