Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- String Formatting
- Indexing and Slicing
- Set Comprehensions
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Python Core Concepts
Python Collections
- Python collections ChainMap
- Python collections
- Python collections ChainMap<
- Python counters
- Python deque
- Python dictionary
- Python Lists
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
While Loops in Python
Looping is a vital concept in any programming language. It helps repeat certain operations without rewriting code. Python supports two main types of loops: for
and while
. While for
loops are often used when you know how many times you want to iterate, while
loops are better suited when the repetition depends on a condition being met.
In this detailed, beginner-friendly article, you’ll learn everything you need to know about while
loops in Python—what they are, how they work, common use cases, potential pitfalls, and real-world examples to help you code smarter.
📌 Why Learn While Loops?
You’ll encounter many situations where you need to keep running a piece of code until a condition changes. For example:
- Continuously accepting user input until they type “exit”
- Waiting for a file to be downloaded completely
- Repeating a task while data is being processed
In such cases, a while
loop is the perfect tool. It allows you to loop indefinitely—or until a certain condition is no longer true.
✅ Prerequisites
Before diving into while loops, you should be comfortable with:
- Python variables
- Boolean expressions
- Basic comparison and logical operators (
==
,!=
,<
,>
,and
,or
) - Python syntax and indentation
🔍 What Is a While Loop?
A while
loop in Python repeatedly executes a block of code as long as a specified condition remains True
.
The syntax looks like this:
while condition:
# Code to execute while condition is True
Once the condition becomes False
, the loop stops.
🧠 Example 1: Basic While Loop
count = 1
while count <= 5:
print("Count is:", count)
count += 1
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
In this example, the loop runs five times and exits when count > 5
.
🔄 Difference Between while
and for
Feature | while Loop | for Loop |
---|---|---|
Loop type | Condition-based | Sequence-based |
Use case | Repeat until condition is False | Repeat for known number of items |
Flexibility | More control, but prone to bugs | More concise and readable |
🧪 Example 2: User Input Loop
command = ""
while command.lower() != "exit":
command = input("Enter command (type 'exit' to stop): ")
This loop continues asking the user for input until they type “exit”.
🔁 Example 3: Summing Numbers
total = 0
num = 1
while num <= 10:
total += num
num += 1
print("Sum:", total)
This sums all numbers from 1 to 10 using a while
loop.
⚠️ Infinite Loops in Python
A common issue with while
loops is accidentally creating an infinite loop. This happens when the condition never becomes False
.
while True:
print("This will run forever!")
To stop such loops, you must:
- Use a
break
statement - Ensure your condition will eventually become false
🛑 Using break
in While Loops
break
immediately stops the loop, even if the condition is still True
.
Example:
i = 0
while True:
print(i)
i += 1
if i == 5:
break
This loop would run forever without the break
condition.
🔃 Using continue
in While Loops
continue
skips the current iteration and goes back to check the condition again.
Example:
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue
print(num)
This prints only odd numbers from 1 to 9.
➕ else
Clause with While Loops
Python allows you to use an else
block with loops, which runs only if the loop exits normally (not by break
).
Example:
i = 1
while i <= 5:
print(i)
i += 1
else:
print("Loop finished successfully.")
✅ Real-World Use Cases
1. Repeated User Authentication:
password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted.")
2. Countdown Timer:
import time
n = 5
while n > 0:
print(n)
time.sleep(1)
n -= 1
print("Time's up!")
3. Data Validation:
age = -1
while age < 0:
age = int(input("Enter a valid age: "))
4. Menu System:
choice = ""
while choice != "q":
print("Menu: [a]dd, [d]elete, [q]uit")
choice = input("Choose an option: ")
5. Retry Logic:
attempt = 0
while attempt < 3:
pin = input("Enter PIN: ")
if pin == "1234":
print("Welcome!")
break
attempt += 1
else:
print("Account locked.")
⚠️ Common Mistakes
- Forgetting to update the variable inside the loop (infinite loop risk)
- Confusing assignment (
=
) with comparison (==
) - Not planning for loop exit conditions
- Indentation errors
🌟 Best Practices
- Always ensure the loop condition will eventually become false.
- Avoid overly complex conditions.
- Use
break
sparingly—it can make loops harder to debug. - Use meaningful variable names (e.g.,
attempt
,retry
,count
). - Combine with input validation for real-world scenarios.
while
loops in Python give you flexible control to repeat tasks based on conditions, not just sequences. From waiting for user input to retrying actions or validating data, the while
loop is a key tool in your programming toolkit.
By understanding the logic behind the loop, practicing different examples, and being aware of common mistakes, you’ll be able to write cleaner, safer, and more efficient code.