While loop

UpComing SoftWare Training Demos

πŸš€ *Gen AI EngineerΒ Telugu (Production Focused)*
πŸ—“οΈ *Date:* 30th Sept 2026, 07:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/gr
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/gw
πŸ’‘*Course Content:*
https://www.vlrt.in/ai
▢️ *Demo Videos:*
https://www.vlrt.in/gv

πŸš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
πŸ—“οΈ *Date:* 30th Sept 2026, 08:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/7r
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/7w
πŸ’‘*Course Content:*
https://www.vlrt.in/7c
▢️ *Demo Videos:*
https://www.vlrt.in/7v

πŸš€ *Vulnerability Management Training Demo*
πŸ—“οΈ *Date:* 30th Sept 2026, 09:00 AM IST
πŸ“*Register Now!:*
https://www.vlrt.in/vr
πŸ‘₯ *Join Community:*
https://www.vlrt.in/cw
πŸ’‘ *Course Content:*
https://www.vlrt.in/vc
▢️ *Demo Videos:*
https://www.vlrt.in/Vm

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

  • positive lookbehind assertion

    A positive lookbehind assertion in Python’s re module is a zero-width assertion that checks if the pattern that precedes it is present, without including that pattern in the overall match. It’s the opposite of a lookahead. It is written as (?<=…). The key constraint for lookbehind assertions in Python is that the pattern inside the…

  • Default Arguments

    Default Arguments in Python Functions Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead. Basic Syntax python def function_name(parameter=default_value): # function body Simple Examples Example 1: Basic Default Argument python def greet(name=”Guest”): print(f”Hello, {name}!”)…

  • How to create Class

    πŸŸ₯ Rectangle Properties Properties are the nouns that describe a rectangle. They are the characteristics that define a specific rectangle’s dimensions and position. Examples: πŸ“ Rectangle Methods Methods are the verbs that describe what a rectangle can do or what can be done to it. They are the actions that allow you to calculate information…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”β€”the regex engine looks ahead in the string to see if the pattern inside…

Leave a Reply

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