Python While Loop Syntax And Examples

The while loop in Python is a powerful construct that allows you to execute a block of code repeatedly as long as a specified condition remains true.

This provides a flexible way to implement loops when the exact number of iterations is unknown beforehand.

In this guide, we'll explore the syntax of the while loop and provide examples to illustrate its usage.

Syntax of the while Loop:

The basic syntax of a while loop in Python is as follows:

while condition:
    # Code to execute as long as the condition is True

The code block inside the while loop is indented and executed repeatedly until the specified condition evaluates to False.

Example 1: Simple while Loop

Let's start with a basic example where a while loop is used to print numbers from 1 to 5:

count = 1

while count <= 5:
    print(count)
    count += 1

In this example, the while loop continues to execute as long as the condition count <= 5 remains true.

The print(count) statement outputs the current value of count, and count += 1 increments the value of count in each iteration.

Example 2: Infinite Loop with while True

An interesting use of the while loop is to create an infinite loop using while True.

Here's an example where the loop continues until the user enters a specific value:

user_input = ""

while user_input != "exit":
    user_input = input("Enter a value (type 'exit' to stop): ")
    print(f"You entered: {user_input}")

In this example, the loop continues as long as the user_input is not equal to "exit". The user is prompted to enter a value, and the program prints the entered value.

Example 3: while Loop with break

The break statement can be used to exit a while loop prematurely based on a certain condition.

Here's an example where the loop stops when a specific number is reached:

count = 1

while True:
    print(count)
    count += 1

    if count > 5:
        break

In this example, the loop condition is True, creating an infinite loop. However, the if count > 5: break statement is used to exit the loop when count exceeds 5.

Example 4: while Loop with continue

The continue statement is used to skip the rest of the code inside the loop for the current iteration and move to the next one. Here's an example where even numbers are skipped:

number = 1

while number <= 10:
    if number % 2 == 0:
        number += 1
        continue

    print(number)
    number += 1

In this example, if number is even, the continue statement skips the print(number) statement, and the loop moves on to the next iteration.

Conclusion:

The while loop is a valuable tool in Python for creating dynamic and flexible loops.

Whether you're iterating until a certain condition is met or implementing infinite loops with user input, the while loop provides a versatile solution.

Experiment with these examples, and as you become familiar with the while loop, you'll gain a powerful tool for controlling the flow of your Python programs.