Python while Loop

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

Table of Contents

There are two types of loop: Python for Loop and Python while Loop.


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 Example

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

Python-While-Loop
i = 1
while i <= 5:
    print(i)
    i = i + 1

Code Explanation

  • Line 1: Sets up a variable i with a value 1. We'll use this to keep track of which number we're on.
  • Line 2: Condition that keeps the loop going. As long as i is less than or equal to 5, the loop will continue.
    • Line 3: Prints the current value of i.
    • Line 4: 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


How Python while Loop Works

Here’s how a Python while loop in Python works step-by-step:

Loop Structure

while :
    # 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 an example:

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!")

Code Explanation

  • Line 1: 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.

Using break with 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 an example:

Example 1

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

Code Explanation

  • Line 1: Initializes a variable named count and assigns it the value 0.
  • Line 2: 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: 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: 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

Code 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: 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


Using continue with 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.

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

Code 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: Only executes if i is even and prints the current value.
    • Line 6: Updates the counter.

Using pass with 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.

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)
    # ...

Code Explanation

  • Line 1: 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: Though not shown here, this section would contain the logic to exit the game when necessary.

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:

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.

Code 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: 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: 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

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


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:

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

Example

while True:
    print("Hello")

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

Code Explanation

  • Line 1: Creates the infinite loop condition.
    • Line 2: This line keeps printing "Hello" as long as the loop runs.

Python Reference

Python while Loop