DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
Getting Started
01
What is Python and Why Learn It in 2026
02
Installing Python on Windows, Mac, and Linux
03
Setting up VS Code / PyCharm for Python
04
Understanding the Python Interpreter and REPL
05
Writing and Running Your First Python Program
06
Python Syntax and Indentation Rules
Variables and Data Types
01
Variables and Naming Conventions in Python
02
Numbers in Python (int, float, complex)
03
Strings and String Methods in Python
04
Booleans in Python
05
Type Conversion / Casting in Python
06
Understanding the None Type in Python
Operators
01
Arithmetic Operators in Python
02
Comparison Operators in Python
03
Logical Operators in Python
04
Assignment Operators in Python
05
Bitwise Operators in Python
06
Identity (is) and Membership (in) Operators
07
Walrus Operator (:=) in Python
Input, Output & Strings
01
input() and print() Functions in Python
02
f-strings and String Formatting in Python
03
String Slicing and Indexing in Python
04
Common String Methods (split, join, strip, replace)
05
Escape Characters in Python Strings
Control Flow
01
if, elif, else Statements in Python
02
Nested Conditionals in Python
03
for Loops in Python
04
while Loops in Python
05
break, continue, and pass Statements
06
Loop with else Clause in Python
07
match-case (Structural Pattern Matching)
Data Structures
01
Python Lists: Creation, Indexing, Slicing, Methods
02
Python Tuples and Immutability
03
Python Sets and Set Operations
04
Python Dictionaries: Keys, Values, and Methods
05
List Comprehensions in Python
06
Dictionary & Set Comprehensions in Python
07
Working with Nested Lists and Dictionaries
Functions
01
Defining and Calling Functions in Python
02
Function Arguments: Positional, Keyword, Default
03
*args and **kwargs in Python
04
Return Statements in Python Functions
05
Lambda Functions in Python
06
Recursion in Python
07
Variable Scope: Local, Global, Nonlocal
08
Docstrings and Function Annotations
Functional Programming Basics
01
map(), filter(), and reduce() in Python
02
Closures in Python Explained
03
Python Decorators: Basic to Advanced
04
Generators and yield in Python
Object-Oriented Programming (OOP)
01
Classes and Objects in Python
02
The init Constructor in Python
03
Instance vs Class Variables in Python
04
Inheritance in Python (Single, Multiple, Multilevel)
05
Polymorphism in Python
06
Encapsulation in Python
07
Abstraction in Python with the abc Module
08
Magic/Dunder Methods in Python
09
Static and Class Methods in Python
10
The @property Decorator in Python
11
Python Dataclasses Explained
Error Handling
01
try, except, finally in Python
02
Handling Multiple Exceptions in Python
03
Raising Custom Exceptions in Python
04
Understanding Python's Exception Hierarchy
05
Assertions in Python
File Handling
01
Reading and Writing Text Files in Python
02
Working with the with Statement in Python
03
Working with CSV Files in Python
04
Working with JSON Files in Python
05
Working with Directories (os, pathlib) in Python
Modules and Packages
01
Importing Built-in Modules in Python
02
Creating Your Own Modules in Python
03
Understanding Packages and init.py
04
Python Standard Library Overview
05
Installing Packages with pip
Advanced Core Concepts
01
Iterators and Iterables in Python
02
Context Managers in Python (with, contextlib)
03
Multithreading Basics in Python
04
Multiprocessing Basics in Python
05
Asyncio Basics: async/await in Python
06
Memory Management and Garbage Collection in Python
07
Type Hints in Python (typing module)

while Loops in Python

Not every repetition in code has a known number of steps ahead of time. Sometimes you just need to keep going "while" something is true — waiting for valid input, running a game loop, retrying until something succeeds. That's what the python while loop is for, and it comes with its own set of patterns and pitfalls worth understanding well.

Introduction: What Is a while Loop?

A while loop repeats a block of code for as long as a condition remains True. Once the condition becomes False, the loop stops.

count = 0

while count < 5:
    print(count)
    count += 1
# 0 1 2 3 4
while vs. for: the key difference

The earlier article in this series covered for loops, which iterate over a known collection — a list, a string, a range — a fixed, predictable number of times. while loops are for a different situation entirely: repeating something an unknown number of times, based on a condition that depends on what happens during the loop itself. You don't know in advance how many times a while loop will run — it depends entirely on when the condition eventually becomes False.

Basic syntax
while condition:
    # runs repeatedly as long as condition is True
A simple countdown example
count = 5

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

print("Liftoff!")
# 5
# 4
# 3
# 2
# 1
# Liftoff!

Avoiding Infinite Loops

Why the loop variable must change

This is the single most important habit to build with while loops: something inside the loop body needs to actually change the condition's outcome, or the loop will run forever. Forgetting this is an extremely common beginner mistake:

# DON'T DO THIS — count never changes, so the condition stays True forever
count = 0
while count < 5:
    print(count)
    # forgot to increment count — this is a python infinite loop

If you accidentally run something like this, your program will appear to hang, endlessly printing 0 forever, and you'll need to manually interrupt it (usually Ctrl+C in a terminal).

Intentional infinite loops

That said, an infinite loop isn't always a mistake — while True: is a common, entirely valid pattern for situations where you genuinely want the loop to keep running until something inside the loop explicitly decides to stop it:

while True:
    # runs forever, until something inside explicitly breaks out
    pass

This shows up constantly in real programs: game loops that keep running until the player quits, servers that keep listening for connections, or programs that keep prompting for input until it's valid. The key difference from an accidental infinite loop is intent — you're deliberately choosing True as the condition, with a clear plan for exiting from inside.

Safely exiting an intentional infinite loop

The standard way to exit a while True: loop is with break, covered in detail next:

while True:
    resp input("Type 'quit' to exit: ")
    if resp= "quit":
        break

Controlling the Loop: break and continue

break: exit immediately

break stops the loop entirely, regardless of what the loop's condition currently evaluates to:

number = 0

while number < 100:
    if number == 5:
        break
    print(number)
    number += 1
# 0 1 2 3 4

Even though the condition number < 100 is still True when the loop exits, break overrides it and stops the loop immediately once number reaches 5.

continue: skip to the next check

continue skips the rest of the current iteration's code and jumps straight back to re-checking the loop's condition:

number = 0

while number < 10:
    number += 1
    if number % 2 == 0:
        continue
    print(number)
# 1 3 5 7 9

Here, whenever number is even, continue skips the print() line for that iteration entirely — but the loop keeps running, incrementing and re-checking on the next pass.

A word of caution with continue in while loops specifically: make sure whatever needs to change for the condition to eventually become False happens before the continue line, not after — otherwise you can accidentally create the exact infinite loop covered in the previous section, since continue skips everything below it on that pass.

The else Clause on while Loops

What it does

Like for loops, while loops support an else clause — and it behaves the same way: the else block runs only if the loop finished naturally, meaning the condition eventually became False on its own, rather than the loop being cut short with a break.

count = 0

while count < 3:
    print(count)
    count += 1
else:
    print("Loop finished normally")
# 0
# 1
# 2
# Loop finished normally

If a break had interrupted the loop instead, the else block would be skipped entirely.

Why this is useful

This construct genuinely earns its place for a specific kind of logic: "keep trying something; if you eventually find or achieve what you were looking for, break out and handle that case; but if you run out of chances without success, do something else" — all without needing a separate flag variable to track which outcome occurred.

Practical example: a number-guessing game
import random

secret_number = random.randint(1, 10)
attempts_remaining = 3

while attempts_remaining > 0:
    guess = int(input("Guess the number (1-10): "))
    if guess == secret_number:
        print("Correct! You win!")
        break
    attempts_remaining -= 1
    print(f"Wrong. {attempts_remaining} attempts left.")
else:
    print(f"Out of attempts! The number was {secret_number}.")

The else block here only runs if the player never guessed correctly — if they had, the break on a correct guess would have skipped it entirely. This is a clean way to express "did they succeed, or did they run out of tries?" without a separate won = False variable that you'd otherwise need to set and check manually.

Practical Example: Input Validation Loop

One of the most common real-world uses of a while loop is repeatedly asking for input until it's actually valid — a pattern you'll write constantly once you start building anything interactive.

while True:
    user_input = input("Enter a number between 1 and 10: ")

    if not user_input.isdigit():
        print("That's not a valid number. Try again.")
        continue

    number = int(user_input)

    if 1 <= number <= 10:
        print(f"Thanks! You entered {number}.")
        break
    else:
        print("Out of range. Try again.")

This combines several patterns from this article into one clean, practical loop: while True: provides the "keep asking" behavior, continue re-prompts immediately when the input isn't even a valid number, and break exits once a genuinely valid number is entered. It's the same underlying shape you'd use for a password prompt, a menu selection, or any situation where you need to keep asking until you get something usable.

Best-practice note: choosing between for and while

As a general rule: reach for a for loop whenever you're iterating over a known collection or a fixed range — a list, a string, range(10). Reserve while for situations genuinely driven by a condition rather than a known sequence — waiting for valid input, running until some external state changes, or repeating until a specific goal is reached. Using a while loop where a for loop would fit more naturally (or vice versa) usually still works, but it tends to produce more awkward, harder-to-follow code than picking the tool that actually matches the shape of the problem.

PREVIOUSNEXT LESSON