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

  • Date/Time Objects

    Creating and Manipulating Date/Time Objects in Python 1. Creating Date and Time Objects Creating Date Objects python from datetime import date, time, datetime # Create date objects date1 = date(2023, 12, 25) # Christmas 2023 date2 = date(2024, 1, 1) # New Year 2024 date3 = date(2023, 6, 15) # Random date print(“Date Objects:”) print(f”Christmas:…

  • For Loop in Python

    A for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or any other iterable object. Unlike a while loop that runs as long as a condition is true, a for loop runs a specific number of times—once for each item in the sequence. The…

  • Python timedelta Explained

    Python timedelta Explained timedelta is a class in Python’s datetime module that represents a duration – the difference between two dates or times. It’s incredibly useful for date and time arithmetic. Importing timedelta python from datetime import timedelta, datetime, date Basic Syntax python timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Examples 1. Basic timedelta Creation python from datetime…

  • Mathematical Functions

    1. abs() Syntax: abs(x)Description: Returns the absolute value (non-negative value) of a number. Examples: python # 1. Basic negative numbers print(abs(-10)) # 10 # 2. Positive numbers remain unchanged print(abs(5.5)) # 5.5 # 3. Floating point negative numbers print(abs(-3.14)) # 3.14 # 4. Zero remains zero print(abs(0)) # 0 # 5. Complex numbers (returns magnitude) print(abs(3 +…

  •  Duck Typing

    Python, Polymorphism allows us to use a single interface (like a function or a method) for objects of different types. Duck Typing is a specific style of polymorphism common in dynamically-typed languages like Python. What is Duck Typing? 🦆 The name comes from the saying: “If it walks like a duck and it quacks like…

  • re.I, re.S, re.X

    Python re Flags: re.I, re.S, re.X Explained Flags modify how regular expressions work. They’re used as optional parameters in re functions like re.search(), re.findall(), etc. 1. re.I or re.IGNORECASE Purpose: Makes the pattern matching case-insensitive Without re.I (Case-sensitive): python import re text = “Hello WORLD hello World” # Case-sensitive search matches = re.findall(r’hello’, text) print(“Case-sensitive:”, matches) # Output: [‘hello’] # Only finds lowercase…

Leave a Reply

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