MyInternships.in

Python Control Flow

Python While Loops

A while loop repeats a block of code as long as a condition stays True, making it ideal when you don't know in advance how many times you need to repeat something.


while Loop Syntax

A while loop starts with the keyword while, followed by a condition and a colon. Python checks the condition before each pass; the moment it becomes False, the loop stops and execution continues after the loop.

Basic while loop
Python
count = 1
while count <= 5:
    print(count)
    count += 1

Using a Counter Variable

Most while loops rely on a counter variable that changes on each iteration, eventually making the condition False. Forgetting to update the counter is the most common beginner bug.

⚠️

If you never update the variable used in the condition, the loop never ends. Always double-check that something inside the loop moves it toward a False condition.

Infinite Loops

A loop written as while True: runs forever unless something inside it stops execution, usually with a break statement. Infinite loops are useful for programs that keep running until the user chooses to quit, like menus.

Infinite loop with break
Python
while True:
    answer = input("Type quit to stop: ")
    if answer == "quit":
        break
    print("You typed:", answer)

The while-else Clause

A while loop can have an optional else block. The else runs only if the loop finishes naturally because its condition became False — it is skipped if the loop exits early via break.

while with else
Python
n = 1
while n < 4:
    print(n)
    n += 1
else:
    print("Loop finished normally")

Combining while with break

You can exit a while loop early with break, even if its condition is still True. This is common when searching for something and you want to stop as soon as it is found.

Searching with break
Python
numbers = [4, 9, 15, 22, 30]
index = 0
while index < len(numbers):
    if numbers[index] == 15:
        print("Found at index", index)
        break
    index += 1
💡

Prefer a for loop when you know exactly how many times to repeat (like looping over a list). Use while when repetition depends on a condition that changes at runtime.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships