Master Python Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

While Loop

A while loop repeatedly executes a block of code as long as a specified condition remains True.

Python While Loop

At CIIT Training Institute, loops are explained using practical examples so students can understand how repetition works in real applications.

The while loop is especially useful when we do not know exactly how many times a block of code needs to execute. The loop continues until its condition becomes False.

What is a While Loop?

A while loop checks a condition before every iteration. If the condition is True, the loop body executes.

After executing the loop body, Python checks the condition again.

This process continues until the condition becomes False.

While Loop Flow

Start
Check Condition
↓
Condition is True?
Yes
Execute Loop Body
↓
Update Variable
↓
Check Condition Again
No
Exit Loop

The most important part of a while loop is making sure that the condition eventually becomes False.

While Loop Syntax

while condition:
    # code to execute

Example:

count = 1

while count <= 5:
    print(count)
    count = count + 1
Output
1
2
3
4
5

How While Loop Works Step by Step

Consider the following code:

count = 1

while count <= 3:
    print(count)
    count = count + 1
Iteration count Condition Action
1 1 1 <= 3 → True Print 1
2 2 2 <= 3 → True Print 2
3 3 3 <= 3 → True Print 3
4 4 4 <= 3 → False Loop stops

Increment in While Loop

Usually, we update the loop variable inside the loop. This is called an increment.

number = 1

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

The statement number += 1 increases the value by one after every iteration.

Decrement in While Loop

We can also decrease the value after every iteration.

number = 5

while number >= 1:
    print(number)
    number -= 1
Output
5
4
3
2
1

While Loop With User Input

A while loop is useful when we want to keep asking the user for input until a particular value is entered.

password = ""

while password != "python123":

    password = input("Enter password: ")

print("Login successful!")

The loop continues until the user enters the correct password.

Example: Menu Program 📩🫠

A while loop can be used to repeatedly display a menu until the user chooses to exit.

choice = 0

while choice != 3:

    print("1. Python Course")
    print("2. .NET Course")
    print("3. Exit")

    choice = int(input("Enter your choice: "))

print("Program ended.")
Output
1. Python Course
2. .NET Course
3. Exit
Enter your choice: 3
Program ended.

This type of logic is commonly used in menu-driven programs.

break With While Loop

The break statement immediately terminates the loop.

number = 1

while number <= 10:

    if number == 5:
        break

    print(number)
    number += 1
Output
1
2
3
4

When number becomes 5, the break statement stops the loop.

continue With While Loop

The continue statement skips the current iteration and moves to the next iteration.

number = 0

while number < 5:

    number += 1

    if number == 3:
        continue

    print(number)
Output
1
2
4
5

Number 3 is skipped, while the remaining iterations continue normally.

pass With While Loop

The pass statement does nothing. It is used when Python requires a statement but we do not want to execute any action yet.

number = 1

while number <= 3:

    if number == 2:
        pass

    print(number)
    number += 1
Output
1
2
3

Unlike break, pass does not stop the loop.

Infinite While Loop

If the condition of a while loop never becomes False, the loop can continue indefinitely.

number = 1

while number <= 5:
    print(number)
Problem: The value of number is never updated, so the condition remains True forever.

Correct version:

number = 1

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

Example: Training Enrollment 📩🫠

Suppose we want to keep accepting student names until the user enters exit.

name = ""

while name.lower() != "exit":

    name = input("Enter student name: ")

    if name.lower() != "exit":
        print("Student registered:", name)
Output
Enter student name: Pradnya
Student registered: Pradnya
Enter student name: Samadhan
Student registered: Samadhan
Enter student name: exit

This pattern is useful when the number of inputs is unknown in advance.

Example: Sum of Numbers 🤓📩

number = 1
total = 0

while number <= 5:

    total += number
    number += 1

print("Total =", total)
Output
Total = 15

Example: Limited Login Attempts 🤓🔓

attempts = 0

while attempts < 3:

    password = input("Enter password: ")

    if password == "python123":
        print("Login successful!")
        break

    print("Incorrect password")

    attempts += 1

else:
    print("Account temporarily locked.")
Output
Enter password: hello
Incorrect password
Enter password: test
Incorrect password
Enter password: python123
Login successful!

This example combines a while loop, if, break and else.

else With While Loop

Python allows an else block with a while loop.

The else block executes when the while condition becomes False normally.

number = 1

while number <= 3:

    print(number)
    number += 1

else:

    print("Loop completed")
Output
1
2
3
Loop completed

If the loop is terminated using break, the else block does not execute.

For Loop vs While Loop

For Loop While Loop
Commonly used for iterating over a collection. Commonly used when repetition depends on a condition.
Often used when the number of iterations is known. Useful when the number of iterations is unknown.
Example: Loop through students. Example: Keep asking until valid input.
Automatically moves to the next item. Programmer usually updates the condition variable.

Common Mistakes in While Loop

Mistake What Happens?
Forgetting the colon Python gives a syntax error.
Incorrect indentation Python cannot correctly identify the loop body.
Not updating the variable Can create an infinite loop.
Wrong condition The loop may execute too many or too few times.
Incorrect use of continue Can accidentally skip important logic or cause an infinite loop if the update is skipped.

Important Interview Points

  • A while loop runs while its condition is True.
  • The condition is checked before every iteration.
  • The loop variable generally needs to be updated.
  • break terminates the loop.
  • continue skips the current iteration.
  • pass performs no operation.
  • A while loop can have an else block.

CIIT Learning Point

Remember: Use a while loop when repetition depends mainly on a condition and the exact number of iterations may not be known beforehand. Always make sure the condition can eventually become False unless an intentional infinite loop is required.

CIIT Practice Tasks

  1. Write a while loop to print numbers from 1 to 10.
  2. Write a while loop to print numbers from 10 to 1.
  3. Accept a number from the user and print its multiplication table using a while loop.
  4. Create a program that repeatedly asks for a password until the correct password is entered.
  5. Create a menu-driven program with options for Python, .NET, Java and Exit.
  6. Create a program that accepts numbers until the user enters 0, then display the total of all entered numbers.

Summary :

A Python while loop repeatedly executes a block of code while a condition remains True. The condition is checked before every iteration, and the loop variable should normally be updated so that the loop can eventually stop. break can be used to terminate the loop, continue can skip an iteration, and pass can act as a placeholder. Python also supports an else block with while loops. While loops are especially useful for user input, menu-driven programs, validation, counters and situations where the number of iterations is not known in advance.