Python While Loop Tutorial

The while loop is a fundamental tool in Python for executing a block of code repeatedly as long as a given condition remains true. This type of loop is useful when the number of iterations isn’t known in advance and is determined by a condition within the loop. In this…

The while loop is a fundamental tool in Python for executing a block of code repeatedly as long as a given condition remains true. This type of loop is useful when the number of iterations isn’t known in advance and is determined by a condition within the loop. In this guide, we’ll cover everything you need to know about Python’s while loop, including examples, how to use break statements, and how to simulate a do while loop in Python.

What Is a while Loop in Python?

A while loop in Python repeatedly executes a block of code as long as a specified condition remains true. It’s a versatile control structure, allowing you to create loops that can run indefinitely or terminate based on conditions you define.

Basic Syntax

The syntax of a while loop in Python is straightforward:

while condition:
    # code to execute
  • condition: This is an expression that is evaluated before each loop iteration. If it’s true, the loop will continue; if it’s false, the loop will stop.
  • code to execute: This block contains the statements that are executed each time the condition is true.

Python while Loop Example

Let’s look at a basic example of a while loop in Python:

count = 1
while count <= 5:
    print(f"Count is {count}")
    count += 1

Output:

Count is 1
Count is 2
Count is 3
Count is 4
Count is 5

In this example, the while loop runs as long as count is less than or equal to 5. Each iteration increments count by 1, and the loop stops when count becomes greater than 5.

Python while Loop with break

Sometimes, you might want to exit a while loop before the condition becomes false. In such cases, you can use the break statement to terminate the loop immediately.

Example: Using break in a while Loop

number = 1
while number <= 10:
    print(number)
    if number == 5:
        break
    number += 1

Output:

1
2
3
4
5

Here, the loop is set to iterate until number is greater than 10, but when number reaches 5, the break statement stops the loop immediately.

do while Loop in Python (Simulating a do while Loop)

Unlike some other programming languages, Python does not have a native do while loop. However, you can simulate a do while loop by using a while loop with a break statement or with a condition that checks at the end of each loop iteration.

Example: Simulating a do while Loop

A do while loop ensures that the loop body executes at least once before checking the condition. Here’s how you might implement this behavior in Python:

while True:
    user_input = input("Enter a number (0 to quit): ")
    if user_input == "0":
        break
    print(f"You entered: {user_input}")

Output (assuming the user enters 5, 9, and then 0):

Enter a number (0 to quit): 5
You entered: 5
Enter a number (0 to quit): 9
You entered: 9
Enter a number (0 to quit): 0

This loop will always run at least once, as the while condition is initially set to True. It stops only when the user enters 0, which triggers the break statement.

Infinite while Loops in Python

An infinite while loop is a loop that never stops because its condition is always true. While infinite loops can be useful, they should be used with caution to avoid unintentional infinite runs.

Example: Creating an Infinite while Loop

while True:
    print("This will run forever unless stopped manually.")

This code will continue printing indefinitely until you manually interrupt it, such as by pressing Ctrl + C in most terminals.

Using while with else

An interesting feature in Python is that you can pair while with else. The else block in a while loop executes only if the while loop completes without encountering a break.

Example: while with else

counter = 1
while counter < 5:
    print(counter)
    counter += 1
else:
    print("Loop completed without a break.")

Output:

1
2
3
4
Loop completed without a break.

If the while loop completes naturally, the else block runs. However, if a break statement interrupts the loop, the else block is skipped.

Practical Examples of Python while Loops

Here are some common scenarios where while loops are particularly useful:

Example 1: User Input Validation

The while loop is ideal for continuously prompting users until they provide a valid input.

while True:
    user_input = input("Enter 'yes' or 'no': ").lower()
    if user_input in ('yes', 'no'):
        print(f"You entered: {user_input}")
        break
    else:
        print("Invalid input, please try again.")

Output if the user enters invalid input initially:

Enter 'yes' or 'no': maybe
Invalid input, please try again.
Enter 'yes' or 'no': yes
You entered: yes

Example 2: Countdown Timer

Here’s a simple countdown timer using a while loop.

import time

countdown = 5
while countdown > 0:
    print(countdown)
    countdown -= 1
    time.sleep(1)  # Pauses for 1 second
print("Time's up!")

Output:

5
4
3
2
1
Time's up!

This example uses the time.sleep() function to create a 1-second delay between each countdown number.

Summary of Python while Loop

The while loop is a versatile and powerful control structure in Python that can help you manage iterative tasks based on conditions. Here’s a recap of key points:

  • Basic Usage: Use a while loop to repeat a block of code as long as a condition is true.
  • break: Use break to exit a while loop before the condition becomes false.
  • Simulating do while Loops: Python doesn’t have a native do while loop, but you can simulate it using a while True loop with break.
  • while else: The else block in a while loop executes only if the loop completes without a break.

Mastering the while loop in Python will give you greater flexibility in handling loops and repetitive tasks. Experiment with while loops in your own projects, and try using break, else, and even simulate do while loops to get a feel for how they work in Python.

CREATE YOUR FREE ACCOUNT & GET OUR

FREE IT LABS

profile avatar

Paul Hill

Paul Hill is the founder of ServerAcademy.com and IT instructor to over 500,000 students online!