Python while Loop

Explore the power of Python while loop for conditional iteration. Learn the syntax, how to use break and continue, and common applications of the while loop in programming.

Python while Loop
Table of Contents

What is a while Loop in Python?

It’s a way to tell your program to do something repeatedly as long as a certain condition is true. Here’s a simplified look at how it works:

Python while Loop Syntax

while  <condition>:
    # code to be repeated

Explanation

  • Line 1: This keyword starts the loop.
    • <condition>: This statement needs to be true for the loop to keep running.
    • Line 2: This part gets run as long as the condition is true. It can be one line or multiple lines of code.

Python while Loop Example

Let’s say we want to print the numbers 1 to 5. Here’s how we can do it with a while loop:

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

Explanation

  • Line 1: This line sets up a variable i with a value 1. We’ll use this to keep track of which number we’re on.
  • Line 2: This is the condition that keeps the loop going. As long as i is less than or equal to 5, the loop will continue.
    • Line 3: This line prints the current value of i.
    • Line 4: This line adds 1 to i after each loop. This way, the next time the loop runs, it will print the next number in sequence.

Output

1
2
3
4
5


Understanding Python while Loop Execution

The execution order of a Python while loop follows a clear pattern:

Syntax

while <condition>:
    # code to be repeated
  1. Condition Check: The loop starts by evaluating the condition.
  2. Code Execution (if True): If the condition is True, the indented code block under “while” is executed.
  3. Back to the Beginning: After the code block finishes, the loop returns to step 1 to check the condition again.
  4. Repeat (if True): If the condition is still True, the loop executes the code block again (steps 2 and 3 repeat).
  5. Loop Exit (if False): Once the condition becomes False, the loop terminates and execution continues to the code after the loop.

Using else with Python while Loops

In Python, a while loop with an else clause lets you add code that runs only if the loop finishes naturally, not because it was interrupted. Here’s the syntax:

Syntax

while  <condition>:
    # code to be repeated
else:
    # code to run after the loop finishes normally

else: This optional clause holds code that only runs after the loop finishes iterating normally, without a break statement.

Let’s see an example. Imagine we’re guessing a number between 1 and 10. The loop keeps asking for guesses until you get it right:

Example

secret_number = 7
guess = 0

while guess != secret_number:
  guess = int(input("Guess a number between 1 and 10: "))
else:
  print("You guessed it!")

Explanation

  • Line 1: This sets the number to guess.
  • Line 2: Initializes a guess variable to track user input.
  • Line 4: The loop runs as long as the guess isn’t the secret number.
    • Line 5: Inside the loop, this line prompts the user for a guess and converts it to a number.
  • Line 6: Since there’s no break statement, this part runs after a correct guess.
    • Line 7: This line congratulates the player for guessing correctly.

Controlling Flow with break in Python while Loops

In Python, the break statement lets you exit a while loop, even if the loop’s condition is still true. It’s useful when you want to stop the loop due to something that happens inside it. Here’s the syntax:

Syntax

while <condition>:
    # code to be repeated
    if <something happens>:
        break
  • Line 3: Inside the loop is a conditional statement that checks if a certain event has occurred.
    • break: If the condition in the if statement becomes true, the break statement immediately exits the entire loop.

Example 1

count = 0
while count < 5:
  print(count)
  if count == 3:
    break
  count += 1

Explanation:

  • Line 1: Initializes a variable named count and assigns it the value 0.
  • Line 2: This line starts the while loop. The loop will continue to execute as long as the condition count < 5 is True.
    • Line 3: Prints the current value of count to the console.
    • Line 4: This line checks if the value of count is equal to 3.
      • break: If the condition in line 4 is True (i.e., count is 3), the break statement is executed. This terminates the loop immediately, even though count is less than 5.
    • Line 6: This line increments the value of count by 1. This line will only be executed if the loop doesn’t break on line 5.

Suppose you search for a cherry in a list. The loop stops once it’s found:

Example 2

fruits = ["apple", "banana", "cherry", "mango", "orange"]
index = 0

while index < len(fruits):
  fruit = fruits[index]
  if fruit == "cherry":
    break

  print(fruit)
  index += 1

Explanation

  • Line 1: Creates a list named fruits containing various fruits.
  • Line 2: Initializes a variable named index and assigns it the value 0. This variable will keep track of the current position in the fruits list.
  • Line 4: This line starts the while loop. The loop continues as long as index is less than the length of the fruits list.
    • Line 5: Retrieves the fruit element at the current index position from the fruits list and assigns it to the variable fruit.
    • Line 6: Checks if the current fruit (stored in fruit) is equal to “cherry“.
      • break: If the condition in line 6 is True (i.e., the current fruit is “cherry“), the break statement is executed. This terminates the loop immediately, even though index might not have iterated through the entire list.
    • Line 9: Prints the current fruit (fruit) to the console. This line will only be executed if the loop doesn’t break on line 7.
    • Line 10: Increments the value of index by 1 to move to the next element in the fruits list for the next loop iteration. This line only executes if the loop doesn’t break.

Output

apple
banana


The continue Statement in Python while Loops

Python’s continue statement lets you skip the remaining code in the current iteration of a while loop and jump back to the beginning to check the condition again. Here’s the syntax:

Syntax

while <condition>:
    # code to be repeated
    if <skip condition>:
        continue

    # rest of the code to be executed (if not skipped)
  • Line 3: This optional conditional statement checks if you want to skip the current iteration.
    • continue: If the if statement’s condition is true, continue jumps back to the start of the loop, effectively skipping the rest of the code in that iteration.
  • Line 6: This part only executes if the continue statement isn’t triggered.

Let’s say you only want to print even numbers from 1 to 10:

Example

i = 1
while i <= 10:
    if i % 2 != 0:  # check if i is odd
        continue  # skip odd numbers
    print(i)
    i = i + 1

Explanation

  • Line 1: Initializes a counter variable.
  • Line 2: The loop runs as long as i is less than or equal to 10.
    • Line 3: This checks if the current value of i is odd (leaves a remainder when divided by 2).
      • Line 4: If i is odd, this jumps back to the beginning of the loop.
    • Line 5: This line only executes if i is even and prints the current value.
    • Line 6: This updates the counter.

The pass Statement in Python while Loops

The pass statement in Python acts as a placeholder within a while loop. While it doesn’t execute any code, it can be useful for maintaining your loop’s structure or future implementation. Here’s the syntax:

Syntax

while <condition>:
    # code to be repeated
    pass  # Placeholder (does nothing)

pass: This statement does nothing but hold its place. It can be used as a reminder to add code later or to maintain the loop structure even if no code is currently needed in that iteration.

Imagine you’re creating a game loop but haven’t filled in the logic yet. The pass statement keeps the loop structure while you develop the game:

Example

game_running = True

while game_running:
    # Game logic would go here (currently empty)
    pass

    # Check for events to end the game (e.g., player quits)
    # ...

Explanation

  • Line 1: This sets a variable to control the loop.
  • Line 3:The loop keeps running as long as game_running is True.
    • Line 4-5: This indented section is a placeholder for the game’s core logic, which isn’t implemented yet. The pass statement maintains the loop structure.
    • Line 7:This section, though not shown here, would contain the logic to exit the game when necessary.

Structuring Nested while Loops in Python

Nested while loops in Python allow you to create loops within loops. The inner loop runs completely for each iteration of the outer loop. Here’s an example structure:

Syntax

while <outer_condition>:
    # outer loop code
    while <inner_condition>:
        # inner loop code

Line 3: This inner loop runs entirely for each outer loop iteration.

Example

rows = 3
columns = 4

# Outer loop for rows
row_counter = 1
while row_counter <= rows:
  # Inner loop for columns
  col_counter = 1
  while col_counter <= columns:
    print("*", end="")  # Print an asterisk without a newline
    col_counter += 1

  print()  # Print a newline after each row
  row_counter += 1

Nested while loops allow you to create loops within loops. The outer loop controls the bigger picture (number of rows in this case), while the inner loop handles the repetitive task within each iteration of the outer loop (printing asterisks in each row). This lets you write code that performs complex tasks involving multiple levels of repetition.

Explanation

  • Line 1: Initializes a variable named rows and assigns it the value 3. This will determine the number of rows to be printed.
  • Line 2: Initializes a variable named columns and assigns it the value 4. This will determine the number of asterisks printed in each row.
  • Line 6: This line starts the outer while loop. The loop repeats as long as row_counter is less than or equal to the number of rows (3 in this case).
    • Line 8: Initializes a variable named col_counter inside the outer loop and assigns it the value 1. This variable will be used to count the number of columns.
    • Line 9: This line starts the inner while loop. The loop repeats as long as col_counter is less than or equal to the number of columns (4 in this case).
      • Line 10: Prints an asterisk (*) to the console without a newline character at the end. This creates a continuous row of asterisks.
      • Line 11: Increments the value of col_counter by 1 to move to the next column within the inner loop.
    • Line 13: Prints a newline character after each outer loop iteration, creating a new row for the next iteration.
    • Line 14: Increments the value of row_counter by 1 to move to the next row within the outer loop.

Output

****
****
****


Handling Infinite Python while Loops

An infinite loop in Python occurs when the condition for a while loop never becomes False, causing the loop to run forever. This can be useful in certain situations, but it’s important to be aware of it and have a way to stop the loop if needed. Here’s how to create an infinite loop:

Syntax

while True:
    # code to be repeated infinitely

Line 1: This is the key part. True is a constant value that never changes, so the loop never finds a reason to stop running.

Warning: Infinite loops can freeze your program and require manual termination.

This code continuously prints “Hello” until you stop the program (usually with Ctrl+C):

Example

while True:
    print("Hello")

Explanation

  • Line 1: This creates the infinite loop condition.
    • Line 2: This line keeps printing “Hello” as long as the loop runs.

Creating Lists with Python while Loops

Two main ways to loop through a list in Python are using a for loop and iterating over the items directly or using a while loop with an index. Here’s how to loop using a for loop:

Python for Loop Syntax

for item in my_list:
    # Do something with each item
  • Line 1: This is the core part. It says, “for each item in my_list, do the following.
  • my_list: This is the list you want to loop through.

For example, this code prints each fruit in a list:

Python for Loop Example

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
  print(fruit)

Explanation

  • Line 1: This line creates a list of fruits.
  • Line 3: The loop iterates over each fruit in the fruits list.
    • Line 4: This line prints the current fruit (“item” in this case) during each iteration.

Output

apple
banana
cherry

Python while Loop Example 1

fruits = ["apple", "banana", "cherry", "orange", "mango"]
index = 0

while index < len(fruits):
  print(fruits[index])
  index += 1

The while loop iterates through each element in the fruits list as long as index is less than the list’s length. Each iteration prints the current fruit using its index and then moves on to the next element. This is a common way to process elements stored in a Python list.

Explanation

  • Line 1: Creates a list named fruits containing various fruits.
  • Line 2: Initializes a variable named index and assigns it the value 0. This variable will be used to keep track of the current position within the fruits list.
  • Line 4: This line starts the while loop. The loop continues as long as the value of index is less than the length of the fruits list (determined by the len function).
    • Line 5: This line retrieves the fruit element at the current index position from the fruits list and prints it to the console.
    • Line 6: Increments the value of index by 1. This moves the loop to the next element in the fruits list during the next iteration.

Output

apple
banana
cherry
orange
mango

Python while Loop Example 2

numbers = [1, 2, 3, 4, 5]
i = 0

while i < len(numbers):
    numbers[i] = numbers[i] * 2
    i += 1
print(numbers)

This code takes a list of numbers and doubles each number inside the list using a while loop.

Explanation:

  • Line 1: Creates a list called numbers and stores the values 1, 2, 3, 4, and 5.
  • Line 2: Initializes a variable named i and sets its value to 0. This variable will be used as a counter.
  • Line 4: Starts a while loop. The len(numbers) function gets the length of the list, so the loop continues as long as i is less than 5 (the length of the list).
    • Line 5: Doubles the current element in the numbers list. It takes the value at the position i, multiplies it by 2, and stores the result back at the same position.
    • Line 6: Increases the value of i by 1, preparing for the next iteration of the loop.
  • Line 7: Prints the final modified numbers list after the loop has finished.

Output

[2, 4, 6, 8, 10]