Python while Loop


In Python, loops are essential constructs that allow repetitive execution of code. One of the most commonly used loops is the while loop. It enables you to repeat a block of code as long as a specified condition is True. If you’re looking to understand how to use the while loop in Python effectively, this post is for you!

In this blog post, we will explain how the while loop works in Python, go through its syntax, and provide several examples to help you learn how to use it in your own programs.


What is a while Loop in Python?

The while loop in Python repeatedly executes a block of code as long as a given condition evaluates to True. Once the condition becomes False, the loop terminates.

Basic Syntax of a while Loop:

while condition:
    # Code to execute while the condition is True
  • condition: An expression that is evaluated before each iteration.
  • The block of code inside the while loop is executed as long as the condition is True.

How the while Loop Works

The while loop begins by checking the condition. If the condition is True, the block of code inside the loop runs. After the block of code is executed, the condition is checked again. If it’s still True, the loop repeats. This continues until the condition becomes False.

Example 1: Basic while Loop

Let’s look at a simple example where we print numbers from 1 to 5.

# Example: Simple while loop
num = 1

while num <= 5:
    print(num)
    num += 1  # Increment num by 1

Output:

1
2
3
4
5

In this example:

  • The loop continues as long as num is less than or equal to 5.
  • After each iteration, num is incremented by 1.
  • Once num becomes 6, the condition num <= 5 becomes False, and the loop stops.

Infinite while Loop

If you’re not careful with your condition, it’s possible to create an infinite loop, where the condition never becomes False. This is often unintentional but can happen if the condition always evaluates to True.

Example 2: Infinite while Loop

# Example: Infinite while loop (never ending)
while True:
    print("This will run forever!")

Warning: The loop above will run infinitely, printing the message repeatedly until you interrupt the program (e.g., by pressing Ctrl+C).

To avoid infinite loops, always ensure that the condition will eventually evaluate to False at some point.


Using break and continue with a while Loop

Python’s while loop can also use break and continue statements for controlling the flow of the loop.

  • break: Terminates the loop immediately.
  • continue: Skips the rest of the code in the current iteration and moves to the next iteration.

Example 3: Using break in a while Loop

# Example: Using break to exit the loop
count = 0

while count < 10:
    if count == 5:
        break  # Exit the loop when count reaches 5
    print(count)
    count += 1

Output:

0
1
2
3
4

In this example:

  • The loop continues until count reaches 5.
  • When count == 5, the break statement is triggered, and the loop exits.

Example 4: Using continue in a while Loop

# Example: Using continue to skip iteration
count = 0

while count < 5:
    count += 1
    if count == 3:
        continue  # Skip printing when count is 3
    print(count)

Output:

1
2
4
5

In this case:

  • When count equals 3, the continue statement causes the loop to skip that iteration and move to the next.

Nested while Loops

Just like other loops, you can also have nested while loops, where one while loop is inside another. This is useful when working with multi-dimensional data or performing repeated tasks within another repeated task.

Example 5: Nested while Loop

# Example: Nested while loop
i = 1

while i <= 3:
    j = 1
    while j <= 2:
        print(f"i={i}, j={j}")
        j += 1
    i += 1

Output:

i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2

In this example:

  • The outer while loop iterates over i from 1 to 3.
  • For each value of i, the inner while loop iterates over j from 1 to 2.

Using else with a while Loop

In Python, you can use the else block with a while loop. The else block runs when the loop condition becomes False and the loop exits normally (i.e., not due to a break statement).

Example 6: else with a while Loop

# Example: Using else with while loop
count = 0

while count < 3:
    print(f"Count is {count}")
    count += 1
else:
    print("Loop completed without a break.")

Output:

Count is 0
Count is 1
Count is 2
Loop completed without a break.

In this example:

  • The else block executes after the loop completes, as the condition count < 3 becomes False.

Practical Example: Guessing Game

Let’s implement a simple guessing game where the program repeatedly asks the user to guess a number until they get it right.

# Example: Guessing game using while loop
secret_number = 7
guess = None

while guess != secret_number:
    guess = int(input("Guess the secret number: "))
    if guess < secret_number:
        print("Too low, try again.")
    elif guess > secret_number:
        print("Too high, try again.")
    else:
        print("Congratulations, you guessed it!")

In this example:

  • The while loop continues asking the user for input until they guess the correct number.
  • The program provides feedback on whether the guess is too low or too high.