How to write while loops in Python
A while loop is used for iterating over a sequence. This artice shows how to use while loops.
A while loop in Python is used to repeatedly execute code as long as the given condition is true.
To use a while loop we use the
while condition: syntax.
i = 1 while i <= 3: print(i) i += 1
1 2 3
Note: For simplicity we iterate over numbers with a number boundary condition (
i <= 3) in the example code. In practice however, a for loop usually is the better choice when we want to loop over numbers. A while loop can be used for more complex conditions.
The break statement¶
break statement can be used for an early stopping of the loop even if the loop condition is still True. Typically this is applied when another condition is met.
i = 1 while i <= 3: print(i) if i == 2: break
A common use case of the
break statement is together with a
while True loop. This loop would run endlessly unless the
break statement is reached.
while True: executed_code() if something_special_happened: break
The continue statement¶
continue statement is used to skip the current iteration.
i = 1 while i <= 3: if i == 2: break print(i)
Note that here the print statement is applied at the end of each iteration, so after the possible
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
PySaaS: The Pure Python SaaS Starter Kit
🚀 Build a software business faster with pure Python: Link*