Home » Python While Loops: A Tutorial

Python While Loops: A Tutorial

A while loop in Python allows you to repeatedly execute a block of code as long as a specified condition is True. The loop keeps running until the condition becomes False, at which point the loop stops.

while loops are useful when you don’t know in advance how many times a block of code needs to be executed.

1. Basic Syntax of a While Loop.

while condition:
    # Code to execute repeatedly

condition: This is a logical expression that evaluates to either True or False. As long as the condition is True, the code inside the loop will keep executing.
The loop body: This is the block of code that gets executed repeatedly as long as the condition is True.

2. Simple While Loop Example

# Example: Simple while loop
count = 1

while count <= 5:
    print("Count:", count)
    count += 1  # Increment the count to avoid infinite loop

# Output:
# Count: 1
# Count: 2
# Count: 3
# Count: 4
# Count: 5

In this example:

The loop will run as long as count <= 5. Once count becomes greater than 5, the loop stops.
count += 1 increments the value of count in each iteration to ensure the loop eventually terminates.

3. Infinite While Loops

A while loop can become an infinite loop if the condition never becomes False. Be careful to modify variables within the loop that affect the condition, or you risk creating a loop that runs indefinitely.

# Example: Infinite loop
while True:
    print("This will run forever unless you break the loop")
    break  # Use 'break' to terminate the infinite loop manually

# Output: This will run forever unless you break the loop

In this example:

The loop is set to run forever with while True, but the break statement is used to exit the loop immediately.

4. Using break to Exit a While Loop

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

Example: Exiting a Loop with break

# Example: Using break to exit a loop
i = 1

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

# Output:
# 1
# 2
# 3
# 4
# 5

In this example:

The loop terminates once i == 5, thanks to the break statement. The loop does not continue for values greater than 5.

5. Using continue to Skip Iterations

The continue statement allows you to skip the current iteration and move to the next one without exiting the loop entirely.

Example: Using continue to Skip Even Numbers

# Example: Using continue to skip even numbers
i = 0

while i < 10:
    i += 1
    if i % 2 == 0:
        continue  # Skip the rest of the loop for even numbers
    print(i)

# Output:
# 1
# 3
# 5
# 7
# 9

In this example:

The continue statement skips the current iteration when i is an even number, so only odd numbers are printed.

6. Using else with a While Loop

You can use an else clause with a while loop. The else block is executed when the loop condition becomes False, and the loop terminates normally (i.e., without encountering a break statement).

Example: While Loop with else

# Example: Using else with a while loop
count = 1

while count <= 5:
    print("Count:", count)
    count += 1
else:
    print("The loop finished execution.")

# Output:
# Count: 1
# Count: 2
# Count: 3
# Count: 4
# Count: 5
# The loop finished execution.

In this example:

The loop executes until count > 5, and then the else block is executed. If the loop encounters a break, the else block will not be executed.

Example: Skipping the else Block with break

# Example: Skipping the else block
i = 1

while i <= 5:
    print(i)
    if i == 3:
        break  # Break the loop when i equals 3
    i += 1
else:
    print("This will not be printed because of the break statement.")

# Output:
# 1
# 2
# 3

Here, the else block is skipped because the loop was terminated using the break statement.

7. Using While Loops with User Input

You can use while loops to repeatedly ask for user input until a certain condition is met, which is useful for creating interactive programs.

Example: Asking for Password Input

# Example: Password checker with while loop
password = ""

while password != "secret":
    password = input("Enter the password: ")

print("Access granted!")

In this example:

The loop continues to ask for the password until the user enters “secret”. Once the correct password is entered, the loop terminates, and the message “Access granted!” is printed.

8. Nested While Loops

A while loop can be nested inside another while loop. This is useful when you need to perform repeated actions in multiple dimensions (e.g., rows and columns).

Example: Printing a Pattern with Nested While Loops

# Example: Nested while loop to print a pattern
i = 1

while i <= 5:
    j = 1
    while j <= i:
        print("*", end="")
        j += 1
    print()  # Move to the next line
    i += 1

# Output:
# *
# **
# ***
# ****
# *****

In this example:

The outer loop controls the number of rows, and the inner loop controls the number of stars (*) in each row.

9. Using while Loops to Simulate Do-While Loop Behavior

Python doesn’t have a built-in do-while loop (where the loop executes at least once before checking the condition). However, you can simulate it with a while loop and a break condition.

Example: Simulating Do-While Loop

# Example: Simulating a do-while loop
while True:
    user_input = input("Enter 'exit' to quit: ")
    if user_input == 'exit':
        break
    print(f"You entered: {user_input}")

In this example:

The loop will run at least once before checking if the user input is ‘exit’, thus mimicking a do-while loop.

10. Practical Example: Number Guessing Game

Here’s a simple number guessing game using a while loop:

# Example: Number guessing game
import random

# Generate a random number between 1 and 10
secret_number = random.randint(1, 10)

# Initialize guess to None
guess = None

# Loop until the user guesses the correct number
while guess != secret_number:
    guess = int(input("Guess the number between 1 and 10: "))
    
    if guess < secret_number: print("Too low!") elif guess > secret_number:
        print("Too high!")

print("Congratulations! You guessed the correct number.")

In this example:

The user is prompted to guess a number until they guess the correct one. The loop continues until the guess matches the secret number, providing feedback on whether the guess was too low or too high.

Summary

A while loop repeats as long as a condition is True. Once the condition becomes False, the loop stops.
break is used to exit the loop prematurely.
continue is used to skip the current iteration and continue with the next one.
You can use an else block with a while loop to execute code after the loop finishes, unless interrupted by break.
Nested while loops allow you to perform repeated actions in multiple dimensions, such as rows and columns.
You can simulate a do-while loop in Python by using a while True loop and a break condition.

By mastering while loops, you can write more efficient and flexible programs that perform repetitive tasks based on conditions.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More