Python While Loop Tutorial

The while loop in Python is used to execute a block of code as long as a specified condition is true. This type of loop is particularly useful when the number of iterations is not known before the loop starts. Below are various examples showcasing the use of while loops in different scenarios.

Basic while Loop

Example:

This loop prints numbers from 0 to 4. The condition x < 5 is checked before each iteration, and the loop continues as long as the condition is true.

The break Statement

You can stop the loop even if the while condition is true by using the break statement.

Example:

This loop will terminate when x is equal to 5.

The continue Statement

The continue statement can be used to skip the current iteration and proceed to the next iteration of the loop.

Example:

This loop prints only odd numbers between 1 and 10 because continue skips the print(x) statement for even numbers.

The else Clause

A while loop can have an optional else block which is executed when the loop condition becomes false.

Example:

This loop prints numbers from 0 to 4, followed by “Loop finished”.

Infinite Loops

A loop becomes infinite if its condition never becomes false. Infinite loops are often used intentionally and must be carefully controlled with break statements.

Example:

This loop will repeatedly ask the user for input until they type “exit”.

Nested while Loops

You can nest while loops inside another while loop.

Example:

This example prints a grid of coordinate pairs from (0, 0) to (2, 2).

Combining while Loops with for Loops

while and for loops can be combined for more complex control flows.

Example:

Similar to the previous example, this prints coordinate pairs but uses a for loop for the inner iteration.

Understanding and effectively using while loops enhances your ability to write programs that require conditional and repeated execution. By mastering while loops along with for loops, you can handle a wide range of programming scenarios in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *