Python While Loops

A while loop allows you to execute a block of code as long as a specified condition is True. This is useful for scenarios where you need to repeat an action until a certain condition changes.

Basic While Loop

The basic syntax of a while loop is as follows:

The while loop will continue to execute the indented code block as long as the condition remains True.

Tutorials dojo strip
Python

In this example, the loop will print the value of count and increment it by 1 each time, until count reaches 5.

Python

While Loop with Else

You can also include an else block with a while loop. The else block will be executed when the condition becomes False.

The else block runs after the while loop completes normally.

Python

Infinite While Loop

An infinite loop occurs when the condition of a while loop never becomes False. This should generally be avoided unless intentionally used (e.g., in servers). An infinite loop will continue to run indefinitely unless externally stopped.

Python

Breaking out of a While Loop

You can use the break statement to exit a while loop prematurely, even if the condition is still True. The break statement immediately terminates the loop.

Python

Skipping Iterations in a While Loop

The continue statement skips the current iteration and moves to the next iteration of the loop. It allows you to skip specific iterations based on a condition.

Python

Python While Loops Example Code

This program uses while loops to print numbers, break out of the loop prematurely, and skip certain iterations.

Python




Python Labs

Tutorials dojo strip