Python While Loops
Discover how to use while loops in Python to execute code repeatedly as long as a specified condition remains true. Learn the syntax and see practical examples of while loops in action.
Python While Loops
Python has two primary loop commands:
while
loopsfor
loops
The while Loop
The while
loop allows us to execute a set of statements as long as a condition is true.
Example
i = 2
while i < 6:
print(i)
i += 1
Output
2
3
4
5
Note: Remember to increment i
, or else the loop will continue forever.
The while
loop requires relevant variables to be ready. In this example, we need to define an indexing variable, i
, which we set to 2.
The break Statement
The break
statement allows us to stop the loop even if the while
condition is true.
Example
i = 2
while i < 6:
print(i)
if i == 4:
break
i += 1
Output
2
3
4
The continue Statement
The continue
statement stops the current iteration and continues with the next.
Example
i = 1
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output
2
4
5
6
The else Statement
The else
statement runs a block of code once when the condition is no longer true.
Example
i = 2
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output
2
3
4
5
i is no longer less than 6