Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ”„ Python While Loop: Complete Guide

Python While Loop - Complete Guide

The while loop repeats code as long as a condition remains True — powerful and flexible!

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • What is a While Loop?
  • While Loop Syntax
  • Flowchart & Execution Flow
  • While Loop Examples
  • Infinite While Loops
  • Else Clause with While
  • Break and Continue
  • Real-World Use Cases
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What the while loop is — understanding condition-based repetition
  • Syntax and structure — writing proper while loops
  • Flowchart and execution — how Python processes while loops
  • Infinite loops — how they happen and how to avoid them
  • Else clause — using else with while loops
  • Break and continue — controlling loop execution
  • Real-world examples — practical applications of while loops
  • Hands-on practice with the interactive editor

What is a While Loop?

A while loop in Python repeatedly executes a block of code as long as a given condition is True. It's a fundamental control flow tool that allows you to automate repetitive tasks where the number of iterations isn't known in advance.

Key insight: The while loop is perfect when you don't know how many times you need to repeat — it keeps going until a condition changes. It's like saying, "Keep doing this while something is true."

Think of a while loop like waiting for a bus. You check the condition ("Is the bus here?"). If false, you wait (repeat the loop). Once true, you stop waiting and get on the bus. The loop continues until the condition becomes false.

While Loop Syntax

The syntax of a while loop is simple and intuitive:

# Syntax
while condition:
    # Code to repeat (the loop body)
    # This runs as long as condition is True

# Example
count = 1
while count <= 5:
    print(f"Count is: {count}")
    count += 1

# Output:
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4
# Count is: 5

šŸ“– Important: The condition is checked before each iteration. If it's True, the loop body executes. If False, the loop ends. This is called a "pre-test" loop because the condition is tested before the code runs.

Key points to remember:

  • The condition must eventually become False to avoid an infinite loop
  • You must change the condition inside the loop (like incrementing a counter)
  • The loop body must be indented (usually 4 spaces)
  • You can use any expression that evaluates to True or False

Flowchart & Execution Flow

Understanding the flow of a while loop helps you write correct code. Here's how Python executes a while loop:

Start
Check Condition
āœ… True
āŒ False
Execute Loop Body
Exit Loop
Go back to condition check
End

Step-by-step execution:

  1. Python evaluates the condition
  2. If True, it executes the loop body and goes back to step 1
  3. If False, it skips the loop body and continues with the code after the loop

While Loop Examples

Let's explore different examples of the while loop in action:

# Example 1: Count from 1 to 10
num = 1
while num <= 10:
    print(num, end=" ")
    num += 1
# Output: 1 2 3 4 5 6 7 8 9 10

# Example 2: Sum of numbers from 1 to 100
total = 0
i = 1
while i <= 100:
    total += i
    i += 1
print(f"\nSum of 1 to 100: {total}")
# Output: Sum of 1 to 100: 5050

# Example 3: Print even numbers
num = 2
while num <= 20:
    print(num, end=" ")
    num += 2
# Output: 2 4 6 8 10 12 14 16 18 20

# Example 4: Countdown timer
countdown = 5
while countdown > 0:
    print(f" {countdown}")
    countdown -= 1
print(" Liftoff!")
# Output:
#  5
#  4
#  3
#  2
#  1
#  Liftoff!

Infinite While Loops

An infinite loop is a loop that never ends because its condition never becomes False. While this can be useful in some cases (like game loops or server programs), it's usually a bug that freezes your program.

#  INFINITE LOOP - DON'T RUN!
# This will run forever
while True:
    print("This never stops!")

# Another infinite loop
count = 1
while count < 10:
    # Forgot to increment count!
    print(count)  # This prints 1 forever

#  BAD: The condition never changes
x = 5
while x > 0:
    print(x)
    # Missing: x -= 1

Warning: Always ensure your loop condition will eventually become False. Common mistakes include forgetting to update the variable that controls the condition or using the wrong condition.

How to stop an infinite loop:

  • Press Ctrl+C (or Cmd+C on Mac) in the terminal
  • Close the terminal/IDE window
  • Use a debugger to pause execution

Else Clause with While

Python allows an else clause with while loops. The else block runs when the loop condition becomes False normally (not when broken).

# Example: else with while
num = 1
while num <= 3:
    print(f"Number: {num}")
    num += 1
else:
    print("Loop completed normally!")

# Output:
# Number: 1
# Number: 2
# Number: 3
# Loop completed normally!

# With break - else doesn't run
num = 1
while num <= 5:
    if num == 3:
        break
    print(num)
    num += 1
else:
    print("This won't run because of break")
# Output: 1 2

šŸ“– Use case: The else clause is useful for checking if a loop was completed or broken. It's often used in search algorithms to indicate if an item was found.

Break and Continue in While Loops

Just like for loops, while loops support break and continue statements:

# break - exits the loop
num = 1
while num <= 10:
    if num == 5:
        break
    print(num, end=" ")
    num += 1
# Output: 1 2 3 4

# continue - skips current iteration
num = 0
while num < 5:
    num += 1
    if num == 3:
        continue
    print(num, end=" ")
# Output: 1 2 4 5

# Using break with user input
while True:
    user_input = input("Type 'quit' to exit: ")
    if user_input.lower() == 'quit':
        break
    print(f"You typed: {user_input}")

Real-World Use Cases

šŸ’” Use Case 1: User Input Validation

# Keep asking until user enters a valid number
valid_input = False
while not valid_input:
    try:
        age = int(input("Enter your age: "))
        if age > 0 and age < 120:
            valid_input = True
            print(f"Your age is: {age}")
        else:
            print("Please enter a valid age (1-119)")
    except ValueError:
        print("Invalid input! Please enter a number.")

šŸ’” Use Case 2: ATM or Banking System

# Simple ATM simulation
balance = 1000
pin = "1234"
attempts = 3

while attempts > 0:
    entered_pin = input("Enter your PIN: ")
    if entered_pin == pin:
        print("āœ… PIN correct!")
        while True:
            print(f"\nBalance: ₹{balance}")
            print("1. Withdraw")
            print("2. Deposit")
            print("3. Exit")
            choice = input("Choose option: ")
            if choice == "1":
                amount = float(input("Amount to withdraw: "))
                if amount <= balance:
                    balance -= amount
                    print(f"₹{amount} withdrawn. New balance: ₹{balance}")
                else:
                    print("Insufficient balance!")
            elif choice == "2":
                amount = float(input("Amount to deposit: "))
                balance += amount
                print(f"₹{amount} deposited. New balance: ₹{balance}")
            elif choice == "3":
                print("Thank you for banking!")
                break
        break
    else:
        attempts -= 1
        print(f"āŒ Wrong PIN. {attempts} attempts remaining.")
else:
    print("šŸ”’ Account locked due to too many failed attempts.")

šŸ’” Use Case 3: Game Loop

# Simple guessing game
import random

secret_number = random.randint(1, 10)
guess = None
attempts = 0

print("šŸŽÆ Guess the number (1-10)!")
while guess != secret_number:
    try:
        guess = int(input("Your guess: "))
        attempts += 1
        if guess < secret_number:
            print("šŸ“ˆ Too low!")
        elif guess > secret_number:
            print("šŸ“‰ Too high!")
        else:
            print(f"šŸŽ‰ Correct! You got it in {attempts} attempts!")
    except ValueError:
        print("āŒ Please enter a valid number!")

Try It Yourself!

Experiment with while loops directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
WHILE LOOP DEMONSTRATION
========================================

1. BASIC WHILE LOOP
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

2. SUM OF NUMBERS
Sum of 1 to 10: 55

3. BREAK STATEMENT
1 2 3 4

4. CONTINUE STATEMENT
1 2 4 5

5. ELSE CLAUSE
1 2 3
Loop completed!

āœ… Explore the while loop!
šŸ†

šŸŽ‰ You've Learned Python While Loops!

You understand while loop syntax, infinite loops, else clause, break, continue, and real-world applications. These are essential for writing dynamic Python programs!

Quick Quiz – Test Your Knowledge

Let's see what you've learned about while loops:

1. When does a while loop stop executing?
2. What is a common cause of infinite loops?
3. When does the else clause in a while loop execute?
4. Which statement exits the while loop immediately?
5. What does the continue statement do in a while loop?

Frequently Asked Questions

šŸ¤” What's the difference between a while loop and a for loop? ā–¼

A for loop is used when you know how many times you want to iterate (like over a sequence). A while loop is used when you want to repeat until a condition changes, which may be unknown in advance. For loops are safer from infinite loops, while loops give more control.

šŸ”§ Can I use break and continue in the same while loop? ā–¼

Yes! Both break and continue can be used in the same while loop. break exits the loop completely, while continue skips the rest of the current iteration and moves to the next condition check.

šŸ“ How do I avoid infinite loops? ā–¼

To avoid infinite loops: (1) Always update the condition variable inside the loop, (2) Make sure the condition will eventually become False, (3) Use break when needed, and (4) Test your loop with small numbers first to verify it works correctly.

šŸ“Š Can I use a while loop with user input? ā–¼

Absolutely! While loops are commonly used for user input validation. You can keep asking the user for input until they provide valid data. This is one of the most practical uses of while loops in real-world applications.

⚔ Is there a performance difference between while and for loops? ā–¼

In most cases, for loops are slightly faster in Python because the iteration mechanism is optimized in C. However, the performance difference is minimal for most applications. Choose the loop that makes your code more readable and appropriate for the task.

šŸŽÆ Can I nest while loops inside each other? ā–¼

Yes! You can have nested while loops (a while loop inside another while loop). This is useful for working with multi-dimensional data or performing complex iterations where the inner loop runs completely for each iteration of the outer loop.

šŸ“š Where to Go From Here

Now that you've mastered the while loop, here are the next topics to explore:

šŸ”„ Nested While Loop

Learn how to use while loops inside other while loops.

Learn More →

šŸ”„ The for Loop

Master the for loop and compare it with while loops.

Learn More →

šŸ“ While Loop Assignments

Practice what you've learned with coding challenges.

Practice →
šŸ“– Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Introduction to Loops Next: Nested While Loop →