While loop

A while loop in Python is used to repeatedly execute a block of code as long as a given condition remains True. It is particularly useful when you don’t know beforehand how many times the loop needs to run.

Before every iteration, Python evaluates the condition. If it evaluates to True, the code inside the loop executes. Once the condition evaluates to False, the loop terminates, and the program moves on to the next line of code outside the loop.

Basic Syntax

Python

while condition:
    # Code block to execute
    # Ensure there is a way for the condition to eventually become False

Here are 5 detailed examples demonstrating different ways to use while loops.

Example 1: A Basic Counter

The most common use of a while loop is to run a block of code a specific number of times using a counter variable.

Python

count = 1

while count <= 5:
    print(f"Current count is: {count}")
    count += 1  # Crucial: Increment the counter so the loop eventually stops

print("Loop finished!")

How it works:

The loop checks if count is less than or equal to 5. It prints the number, adds 1 to count, and checks the condition again. When count becomes 6, the condition 6 <= 5 is False, and the loop ends.

Example 2: Validating User Input

while loops are excellent for keeping a program running until a user provides a specific or valid input.

Python

user_input = ""

# The loop runs as long as the user doesn't type 'quit'
while user_input.lower() != "quit":
    user_input = input("Type something (or 'quit' to exit): ")
    
    if user_input.lower() != "quit":
        print(f"You typed: {user_input}")

print("Goodbye!")

How it works:

The condition checks the value of user_input. As long as it does not equal “quit”, the loop will continuously prompt the user for new input.

Example 3: Using the break Statement

The break statement allows you to immediately exit a while loop entirely, regardless of whether the main condition is still True. This is often used with infinite loops (while True:).

Python

number = 10

while True:  # This creates an infinite loop
    print(f"Processing number: {number}")
    number -= 2
    
    if number <= 0:
        print("Number reached 0 or less. Breaking the loop.")
        break  # Forces the loop to end immediately

print("Out of the loop.")

How it works:

while True means the loop condition will never evaluate to False on its own. The only way out is the break statement, which is triggered when number drops to 0 or below.

Example 4: Using the continue Statement

The continue statement stops the current iteration of the loop and immediately jumps back to the top to evaluate the condition again. It skips the rest of the code inside the loop for that specific iteration.

Python

count = 0

while count < 6:
    count += 1
    
    # Skip even numbers
    if count % 2 == 0:
        continue 
        
    print(f"Odd number found: {count}")

How it works:

When count is an even number (like 2, 4, or 6), the continue statement is triggered. Python skips the print function and goes straight back to the while count < 6 check.

Example 5: The while...else Clause

Python is unique in that it allows an else block at the end of a while loop. The else block will execute only if the loop finishes naturally (meaning the condition became False). It will not execute if the loop is terminated by a break statement.

Python

search_item = 5
current_num = 1

while current_num <= 3:
    if current_num == search_item:
        print(f"Found {search_item}!")
        break
    current_num += 1
else:
    # This runs because the loop finished without hitting the 'break'
    print(f"Item {search_item} was not found in the sequence.")

How it works:

The loop searches for the number 5, but only counts up to 3. Because it never finds 5, the break statement is never executed. Since the loop terminates naturally when current_num reaches 4, the else block is triggered.

Here is a collection of 20 Python while loop examples, structured from fundamental concepts to more practical applications. You can use these to gradually build your students’ understanding of iteration, condition checking, and loop control.

Part 1: Basic Counting and Iteration

These examples establish the core mechanics of a while loop: initialization, condition, and increment/decrement.

1. Simple Counter (1 to 5)

Demonstrates the most basic form of a loop.

Python

i = 1
while i <= 5:
    print("Count:", i)
    i += 1  # Always remind students to increment!

2. Countdown (5 to 1)

Shows how to decrement a value until it reaches a base condition.

Python

countdown = 5
while countdown > 0:
    print(countdown)
    countdown -= 1
print("Blastoff!")

3. Printing Even Numbers

Introduces stepping by values other than 1.

Python

num = 2
while num <= 10:
    print(num)
    num += 2  # Increment by 2

4. Printing Odd Numbers

Similar to the above, but starts at a different initial value.

Python

num = 1
while num <= 10:
    print(num)
    num += 2

5. Sum of First N Natural Numbers

Introduces the concept of an accumulator variable.

Python

n = 5
total = 0
i = 1
while i <= n:
    total += i  # Accumulate the sum
    i += 1
print("Sum is:", total)

Part 2: Mathematical Operations

These loops show how iteration is used to solve standard mathematical problems.

6. Factorial of a Number

A classic algorithmic example for freshers.

Python

num = 5
factorial = 1
while num > 0:
    factorial *= num
    num -= 1
print("Factorial is:", factorial)

7. Multiplication Table

Useful for showing how loops can generate structured data.

Python

multiplier = 7
i = 1
while i <= 10:
    print(f"{multiplier} x {i} = {multiplier * i}")
    i += 1

8. Sum of Digits

Teaches students how to use modulo (%) and floor division (//) to break down numbers.

Python

number = 456
digit_sum = 0
while number > 0:
    digit_sum += number % 10  # Extract last digit
    number //= 10             # Remove last digit
print("Sum of digits:", digit_sum)

9. Reverse a Number

Builds on the previous logic to construct a new integer.

Python

number = 1234
reversed_num = 0
while number > 0:
    remainder = number % 10
    reversed_num = (reversed_num * 10) + remainder
    number //= 10
print("Reversed:", reversed_num)

10. Generating the Fibonacci Sequence

Great for explaining how variables can hand off values to each other.

Python

n_terms = 5
a, b = 0, 1
count = 0
while count < n_terms:
    print(a, end=" ")
    a, b = b, a + b  # Update values simultaneously 
    count += 1

Part 3: Loop Control Statements

Teaching break and continue gives students finer control over execution flow.

11. Using break to Exit Early

Shows how to stop a loop before the main condition evaluates to False.

Python

i = 1
while i <= 10:
    if i == 5:
        print("Breaking the loop at 5")
        break
    print(i)
    i += 1

12. Using continue to Skip an Iteration

Shows how to bypass specific conditions without stopping the whole loop.

Python

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue  # Skips printing '3'
    print(i)

13. The “Do-While” Simulation (Infinite Loop with Break)

Python doesn’t have a native do-while loop, so this is the standard workaround.

Python

while True:
    user_input = "exit"  # Hardcoded for example, usually input()
    print("Running...")
    if user_input == "exit":
        break

Part 4: Data Structures (Lists and Strings)

While for loops are usually better for iterables in Python, doing it with while teaches students about index bounds.

14. Iterating Through a List

Teaches the relationship between loop counters and array/list indices.

Python

fruits = ["apple", "banana", "cherry"]
index = 0
while index < len(fruits):
    print(fruits[index])
    index += 1

15. Iterating Through a String

Treats strings as arrays of characters.

Python

text = "Python"
index = 0
while index < len(text):
    print(text[index])
    index += 1

16. Emptying a List Using pop()

A practical data-processing pattern.

Python

tasks = ["Task 1", "Task 2", "Task 3"]
while tasks:  # Loops as long as the list is not empty
    current = tasks.pop(0)
    print("Processing:", current)

17. Removing All Instances of a Specific Value

Shows a clean way to sanitize a list.

Python

numbers = [1, 2, 3, 2, 4, 2, 5]
while 2 in numbers:
    numbers.remove(2)
print("Cleaned list:", numbers)

Part 5: Logic and Patterns

More advanced loops that require tracking state or multiple variables.

18. Linear Search with a While Loop

A foundational algorithm for computer science students.

Python

data = [10, 20, 30, 40, 50]
target = 30
index = 0
found = False

while index < len(data) and not found:
    if data[index] == target:
        found = True
        print(f"Found {target} at index {index}")
    index += 1

19. Finding the Greatest Common Divisor (Euclidean Algorithm)

A neat, efficient algorithm that relies heavily on a while loop.

Python

a = 48
b = 18
while b != 0:
    temp = b
    b = a % b
    a = temp
print("GCD is:", a)

20. Printing a Right-Angled Triangle Pattern

Nested loops (or string multiplication) to build visual patterns.

Python

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

Similar Posts

  • Classes and Objects in Python

    Classes and Objects in Python What are Classes and Objects? In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). Real-world Analogy Think of a class as a “cookie cutter” and objects as the “cookies” made from it. The cookie cutter defines the shape, and each cookie is an instance of that shape. 1. Using type() function The type() function returns…

  • Python Program to Check Pangram Phrases

    Python Program to Check Pangram Phrases What is a Pangram? A pangram is a sentence or phrase that contains every letter of the alphabet at least once. Method 1: Using Set Operations python def is_pangram_set(phrase): “”” Check if a phrase is a pangram using set operations “”” # Convert to lowercase and remove non-alphabetic characters…

  • break and continue

    In Python, break and continue are loop control statements. They allow you to alter the standard flow of a loop (whether a for loop or a while loop) based on specific conditions. Here is a detailed breakdown of how each statement works, along with examples. The break Statement The break statement is used to completely…

  • What is general-purpose programming language

    A general-purpose programming language is a language designed to be used for a wide variety of tasks and applications, rather than being specialized for a particular domain. They are versatile tools that can be used to build anything from web applications and mobile apps to desktop software, games, and even operating systems. Here’s a breakdown…

  • re.subn()

    Python re.subn() Method Explained The re.subn() method is similar to re.sub() but with one key difference: it returns a tuple containing both the modified string and the number of substitutions made. This is useful when you need to know how many replacements occurred. Syntax python re.subn(pattern, repl, string, count=0, flags=0) Returns: (modified_string, number_of_substitutions) Example 1: Basic Usage with Count Tracking python import re…

Leave a Reply

Your email address will not be published. Required fields are marked *