Popular Searches
Popular Course Categories
Popular Courses

Using while Loops

Loops and Iteration in Python

Using while Loops in Python

Course: Python Programming

Topic: Using while Loops

Course Link: Python Training Course at JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Homepage


1. Introduction to while Loops

A while loop is a control-flow statement in Python that repeatedly executes a block of code as long as a specified condition evaluates to True. It is particularly useful when the number of repetitions is not known in advance and depends on a condition, user input, or a changing value.

For example, a program may continue asking a user to enter a valid password until the correct password is provided. A while loop can also be used for counting, processing data until a condition changes, building menu-driven applications, and running games until the player chooses to exit.

Basic Syntax

while condition:
    # Statements to execute
    # Update the condition or related variables
  • while: Starts the loop.
  • Condition: A Boolean expression evaluated before each iteration.
  • Colon (:): Marks the beginning of the loop body.
  • Indented statements: The code that executes while the condition remains true.
  • Update statement: Often changes a variable so the condition eventually becomes false.

The condition is checked before each iteration. If it is initially false, the loop body does not execute at all.

2. How a while Loop Works

A while loop follows a repeated cycle of checking a condition, executing statements, updating values, and checking the condition again.

  1. Initialize the required variable or state.
  2. Evaluate the loop condition.
  3. If the condition is true, execute the indented loop body.
  4. Update the variable or state that affects the condition.
  5. Return to the condition and evaluate it again.
  6. Stop when the condition becomes false or the loop exits through a control statement such as break.

Example: Counting from 1 to 5

count = 1

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

Output:

1
2
3
4
5

Explanation: The variable count starts at 1. The loop prints its current value and increments it by 1. When count becomes 6, the condition count <= 5 is false, so the loop stops.

3. Understanding Loop Conditions

The condition determines whether the loop continues or terminates. It can use comparison operators, logical operators, Boolean variables, or other expressions that produce a truth value.

Condition Meaning Example Use
count < 10 Continues while count is below 10. Counting iterations.
balance > 0 Continues while the balance is positive. Processing a balance.
password != "python123" Continues while the password is incorrect. Input validation.
choice != "exit" Continues until the user enters exit. Menu-driven programs.
attempts < 3 Continues while fewer than three attempts have been made. Limited retries.

Example: Using a Boolean Condition

is_running = True

while is_running:
    print("The program is running.")
    is_running = False

Output:

The program is running.

Initially, is_running is true, so the loop executes. The assignment is_running = False changes the condition, and the next check ends the loop.

4. Updating Variables Inside a while Loop

In many loops, a variable must change during each iteration. Without an appropriate update, the condition may remain true indefinitely, causing an infinite loop.

Incrementing a Variable

number = 1

while number <= 4:
    print(number)
    number = number + 1

Output:

1
2
3
4

Decrementing a Variable

countdown = 5

while countdown > 0:
    print(countdown)
    countdown -= 1

print("Time is up!")

Output:

5
4
3
2
1
Time is up!

Using Multiplication to Update a Value

number = 2

while number <= 32:
    print(number)
    number *= 2

Output:

2
4
8
16
32

The update operation should always be chosen carefully so that the condition eventually becomes false.

5. Using while Loops with User Input

A common use of while loops is repeatedly accepting input until the user provides an expected value.

Example: Asking for a Positive Number

number = int(input("Enter a positive number: "))

while number <= 0:
    print("Invalid input. Please enter a positive number.")
    number = int(input("Enter a positive number: "))

print("Accepted number:", number)

If the user enters 0 or a negative number, the program asks again. Once a positive integer is entered, the condition becomes false and the program continues.

Example interaction:

Enter a positive number: -3
Invalid input. Please enter a positive number.
Enter a positive number: 0
Invalid input. Please enter a positive number.
Enter a positive number: 8
Accepted number: 8

Important: This example assumes the user enters an integer. If text such as hello is entered, int() raises a ValueError. Input validation with try and except is covered later in these notes.

6. Infinite while Loops

An infinite loop is a loop that does not terminate naturally because its condition remains true. Infinite loops can be intentional, such as in a server or interactive application that waits for commands, but they should have a clear exit mechanism.

Example of an Accidental Infinite Loop

count = 1

while count <= 5:
    print(count)

This code repeatedly prints 1 because count never changes. The condition count <= 5 remains true.

Corrected Version

count = 1

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

Incrementing count allows the loop to reach a terminating condition.

Intentional Infinite Loop

while True:
    command = input("Enter a command (or quit): ").strip().lower()

    if command == "quit":
        print("Program closed.")
        break

    print("You entered:", command)

The condition True never becomes false. The loop ends when the user enters quit and the break statement is executed.

7. The break Statement

The break statement immediately terminates the nearest enclosing loop, regardless of whether its condition is still true. Execution continues with the first statement after the loop.

Example: Stop Counting at 4

number = 1

while number <= 10:
    if number == 4:
        break

    print(number)
    number += 1

print("Loop ended.")

Output:

1
2
3
Loop ended.

When number becomes 4, the condition inside the if statement is true. The break statement ends the loop before 4 is printed.

8. The continue Statement

The continue statement skips the remaining statements in the current iteration and returns to the loop condition. It does not terminate the entire loop.

Example: Skip the Number 3

number = 0

while number < 5:
    number += 1

    if number == 3:
        continue

    print(number)

Output:

1
2
4
5

The variable is incremented before continue executes. This order is important: if the increment were placed after the continue, the value could remain 3 and the loop might never progress.

9. The else Clause with a while Loop

Python allows an optional else clause after a while loop. The else block executes when the loop condition becomes false. It does not execute when the loop is terminated by break.

Example: Loop Completes Normally

number = 1

while number <= 3:
    print(number)
    number += 1
else:
    print("Loop completed normally.")

Output:

1
2
3
Loop completed normally.

Example: Loop Ends with break

number = 1

while number <= 5:
    if number == 3:
        break

    print(number)
    number += 1
else:
    print("Loop completed normally.")

print("Program finished.")

Output:

1
2
Program finished.

The loop exits through break, so the loop's else block is skipped.

10. Using while Loops for Mathematical Calculations

Example 1: Calculate the Sum of Numbers

number = 1
total = 0

while number <= 5:
    total += number
    number += 1

print("Sum:", total)

Output:

Sum: 15

The loop adds 1, 2, 3, 4, and 5 to total. The final sum is 15.

Example 2: Multiplication Table

number = int(input("Enter a number: "))
multiplier = 1

while multiplier <= 10:
    print(number, "x", multiplier, "=", number * multiplier)
    multiplier += 1

Example output for input 5:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Example 3: Calculate a Factorial

The factorial of a non-negative integer is the product of all positive integers up to that number. By definition, the factorial of 0 is 1.

number = int(input("Enter a non-negative integer: "))

if number < 0:
    print("Factorial is not defined for negative integers.")
else:
    factorial = 1
    counter = 1

    while counter <= number:
        factorial *= counter
        counter += 1

    print("Factorial:", factorial)

Example output:

Enter a non-negative integer: 5
Factorial: 120

The program multiplies 1 × 2 × 3 × 4 × 5. When the input is 0, the loop does not execute and the initial value of factorial remains 1.

11. Processing Digits with a while Loop

Because integer division and the modulo operator can extract digits, a while loop is useful for working with individual digits of an integer.

Example: Count the Digits of a Number

number = abs(int(input("Enter an integer: ")))

if number == 0:
    digits = 1
else:
    digits = 0

    while number > 0:
        digits += 1
        number //= 10

print("Number of digits:", digits)

Example output:

Enter an integer: 58291
Number of digits: 5

The // operator performs integer division. Repeatedly dividing by 10 removes the last digit until the number becomes 0. The use of abs() means the minus sign is not counted as a digit.

Example: Reverse an Integer

number = int(input("Enter a non-negative integer: "))

if number < 0:
    print("Please enter a non-negative integer.")
else:
    original = number
    reversed_number = 0

    while number > 0:
        digit = number % 10
        reversed_number = reversed_number * 10 + digit
        number //= 10

    print("Original number:", original)
    print("Reversed number:", reversed_number)

Example output:

Enter a non-negative integer: 1234
Original number: 1234
Reversed number: 4321

For input 0, the reversed result is also 0. This example treats the input as an integer, so leading zeros are not preserved.

12. Using while Loops for Input Validation

Input validation ensures that a program receives acceptable data before processing it. A while loop can repeat a prompt until a valid value is supplied.

Example: Handling Non-Numeric Input

while True:
    user_input = input("Enter your age: ").strip()

    try:
        age = int(user_input)

        if age >= 0:
            print("Accepted age:", age)
            break

        print("Age cannot be negative.")

    except ValueError:
        print("Invalid input. Please enter a whole number.")

Example interaction:

Enter your age: abc
Invalid input. Please enter a whole number.
Enter your age: -2
Age cannot be negative.
Enter your age: 25
Accepted age: 25

The try block attempts to convert the input into an integer. If conversion fails, ValueError is caught and the loop asks again. The break statement runs only after a valid, non-negative age is entered.

13. Building a Menu-Driven Program

Menu-driven applications repeatedly display options and perform an action based on the user's choice. A while loop is suitable because the number of interactions is not known in advance.

Example: Simple Calculator

while True:
    print("\n--- Simple Calculator ---")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Exit")

    choice = input("Choose an option: ").strip()

    if choice == "4":
        print("Calculator closed.")
        break

    if choice not in ("1", "2", "3"):
        print("Invalid option. Try again.")
        continue

    try:
        first = float(input("Enter the first number: "))
        second = float(input("Enter the second number: "))
    except ValueError:
        print("Please enter valid numbers.")
        continue

    if choice == "1":
        print("Result:", first + second)
    elif choice == "2":
        print("Result:", first - second)
    else:
        print("Result:", first * second)

How it works:

  • The loop displays the menu repeatedly.
  • The user chooses an operation.
  • Option 4 exits the application through break.
  • Invalid menu choices are rejected using continue.
  • Numeric conversion errors are handled with try and except.
  • The selected operation is executed and the menu appears again.

14. Using while Loops for a Limited Number of Attempts

Many applications limit how many times a user can retry an operation. The attempt counter must be updated reliably so that the loop eventually terminates.

Example: Three Password Attempts

correct_password = "python123"
attempts = 0
max_attempts = 3

while attempts < max_attempts:
    password = input("Enter password: ")
    attempts += 1

    if password == correct_password:
        print("Access granted.")
        break

    remaining = max_attempts - attempts

    if remaining > 0:
        print("Incorrect password. Attempts remaining:", remaining)
else:
    print("Access denied. Maximum attempts reached.")

The loop's else block runs when all attempts are used without a successful match. If the correct password is entered and break runs, the else block is skipped.

Security note: This is a basic learning example. Real authentication systems should not store plain-text passwords and should use appropriate secure authentication, password hashing, and rate-limiting practices.

15. Nested while Loops

A nested while loop is a while loop placed inside another loop. The inner loop completes its iterations for each iteration of the outer loop, unless a control statement changes the flow.

Example: Display a Small Grid

row = 1

while row <= 3:
    column = 1

    while column <= 3:
        print("*", end=" ")
        column += 1

    print()
    row += 1

Output:

* * *
* * *
* * *

The outer loop controls the rows, while the inner loop prints three stars in each row. The inner counter is reset to 1 at the beginning of every outer iteration.

16. Difference Between while and for Loops

Feature while Loop for Loop
Primary purpose Repeats while a condition is true. Iterates over an iterable or a sequence of values.
Number of iterations May be unknown beforehand. Often determined by the iterable.
Condition checking Explicit condition is checked before each iteration. Continues according to the iterator.
Updating variables Often requires a manual update. The loop advances through the iterable automatically.
Common uses Input validation, retry logic, menus, condition-based repetition. Lists, tuples, strings, ranges, and other iterable objects.

Example Using for

for number in range(1, 6):
    print(number)

Equivalent Example Using while

number = 1

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

Both examples print the numbers from 1 through 5. A for loop is generally convenient for iterating over a known range, while a while loop is often clearer when repetition depends on a condition that changes dynamically.

17. Common Errors When Using while Loops

Error Why It Happens Solution
Infinite loop The condition never becomes false. Update the relevant variable or provide a valid exit condition.
Incorrect indentation Statements are outside the intended loop body. Indent all statements that should repeat consistently.
Wrong comparison operator The loop stops too early or continues too long. Check whether <, <=, >, or >= matches the requirement.
Incorrect counter update The counter may skip values or move in the wrong direction. Verify the increment or decrement operation.
Unintended skipped statements continue runs before necessary updates. Place updates before continue when required.
Input conversion error Text cannot be converted into the requested numeric type. Validate input and handle ValueError.
Off-by-one error The condition includes or excludes an unintended boundary. Trace the first and last iteration carefully.

18. Best Practices for while Loops

  • Make the loop condition easy to understand.
  • Initialize all loop-control variables before the loop begins.
  • Ensure that each iteration makes progress toward termination when appropriate.
  • Use break for a clear early exit rather than complicated nested conditions.
  • Use continue only when skipping the rest of an iteration improves readability.
  • Avoid unnecessary nested loops when a simpler approach is available.
  • Validate user input, particularly when converting strings to numbers.
  • Test boundary cases such as zero, negative numbers, empty input, and the maximum allowed value.
  • Use a clear exit command in interactive loops.
  • For potentially long-running loops, consider timeouts, cancellation, or other appropriate safeguards.

19. Practical Exercises

Exercise 1: Print Even Numbers

Write a program using a while loop to print all even numbers from 2 to 20.

Exercise 2: Sum of Natural Numbers

Ask the user for a positive integer n and calculate the sum of numbers from 1 through n. Validate that the input is positive.

Exercise 3: Guess the Number

Choose a secret number and repeatedly ask the user to guess it. Display whether each guess is too high or too low, and stop when the correct number is guessed.

Exercise 4: Count Down

Ask the user for a positive starting number and print a countdown until 1, followed by a completion message.

Exercise 5: Menu-Based To-Do List

Create a program that repeatedly offers options to add a task, view tasks, or exit. Use a while loop to keep the menu active until the user chooses to exit.

Exercise 6: Find the Sum of Digits

Ask the user for an integer and use a while loop with the modulo and integer-division operators to calculate the sum of its digits.

20. Sample Mini Project: Number Guessing Game

This project demonstrates a while loop, conditional statements, user input, and an attempt counter in a simple interactive program.

secret_number = 7
attempts = 0
max_attempts = 5

print("Welcome to the Number Guessing Game!")
print("Guess a number between 1 and 10.")

while attempts < max_attempts:
    try:
        guess = int(input("Enter your guess: "))
    except ValueError:
        print("Please enter a whole number.")
        continue

    if guess < 1 or guess > 10:
        print("Choose a number between 1 and 10.")
        continue

    attempts += 1

    if guess == secret_number:
        print("Congratulations! You guessed correctly.")
        print("Attempts used:", attempts)
        break
    elif guess < secret_number:
        print("Too low. Try again.")
    else:
        print("Too high. Try again.")
else:
    print("Game over. The secret number was", secret_number)

Project Explanation

  • The secret number is set to 7.
  • The loop allows up to five valid guesses.
  • Non-numeric and out-of-range inputs are rejected without consuming a valid attempt.
  • The if, elif, and else branches provide feedback about each guess.
  • The break statement stops the game when the correct number is guessed.
  • The loop's else block displays the answer if all five valid guesses are used without success.

21. Interview Questions and Answers

Q1. What is a while loop in Python?

A while loop repeatedly executes a block of code as long as its condition evaluates to true.

Q2. When should you use a while loop?

Use it when the number of repetitions is not known in advance or when execution should continue until a condition changes, such as during input validation or a menu interaction.

Q3. What happens if the condition is false initially?

The loop body does not execute because Python checks the condition before the first iteration.

Q4. What is an infinite loop?

An infinite loop continues without terminating naturally because its condition remains true. It can be intentional or caused by a missing or incorrect update.

Q5. What is the difference between break and continue?

break terminates the nearest enclosing loop, whereas continue skips the remaining statements in the current iteration and proceeds to the next condition check.

Q6. Can a while loop have an else clause?

Yes. Its else block executes when the loop condition becomes false, but not when the loop is terminated by break.

Q7. Can a while loop be nested inside another while loop?

Yes. Nested loops are useful for tasks such as generating patterns, grids, and combinations of values.

Q8. How can you prevent an infinite loop?

Check that the condition is correct, update relevant variables, and provide a reliable termination path for interactive loops.

Q9. What is an off-by-one error?

It is a logic error in which a loop executes one time too many or one time too few because of an incorrect boundary condition.

Q10. What is the difference between while and for loops?

A while loop repeats while a condition remains true. A for loop iterates through an iterable, such as a list or a range.

22. Quick Revision Checklist

  • Understand the syntax of a while loop.
  • Know that the condition is checked before each iteration.
  • Initialize and update loop-control variables correctly.
  • Identify and prevent accidental infinite loops.
  • Understand break, continue, and the loop else clause.
  • Use loops for counting, calculations, input validation, and menus.
  • Test boundary conditions and invalid inputs.
  • Complete the exercises and mini project.

23. Conclusion

The while loop is an essential Python programming concept for repeating operations while a condition remains true. It is particularly valuable for user-input validation, retry mechanisms, countdowns, mathematical calculations, and interactive programs. Understanding conditions, variable updates, termination logic, and statements such as break and continue helps you write reliable and readable loops.

To continue learning Python programming, explore the Python Training Course at JustAcademy, visit the JustAcademy website, or register for a course demo.

Additional Reference: Python Language Reference – The while Statement

whatsapp