Python Loops Tutorial for Beginners | for Loop, while Loop & Loop Control Statements
In programming, many tasks require repeating the same action multiple times. Imagine sending emails to 1,000 customers, processing thousands of records from a database, or checking attendance for an entire class. Writing the same code repeatedly would be inefficient and difficult to maintain. This is where loops become essential.
Python provides two powerful looping structures: the for loop and the while loop. These allow developers to execute a block of code repeatedly based on a sequence or a condition. Loops are widely used in web development, artificial intelligence, automation, data analysis, and software engineering.
In this lesson, you’ll learn how loops work, when to use different types of loops, how to control loop execution using break, continue, and pass, and how to solve real-world programming problems using iteration.
By the end of this lesson, you’ll be able to write efficient Python programs that automate repetitive tasks and process collections of data with confidence.
Learning Objectives
After completing this lesson, you will be able to:
- Understand the purpose of loops.
- Use
forloops effectively. - Use
whileloops for condition-based repetition. - Iterate through strings, lists, tuples, and dictionaries.
- Use the
range()function. - Control loops using
break,continue, andpass. - Create nested loops.
- Build practical programs using loops.
- Avoid infinite loops.
- Apply loops in real-world software development.
Topics Covered
- Introduction to Loops
- The
forLoop - The
whileLoop - The
range()Function - Nested Loops
- Loop Control Statements
- Infinite Loops
- Real-World Examples
- Best Practices
Detailed Lesson Content
Introduction to Loops
Imagine you own an online shopping website with 10,000 products. You need to calculate a discount for every product. Writing the same calculation 10,000 times would be impossible.
Instead, you write the logic once and let a loop repeat it automatically.
A loop executes a block of code repeatedly until a condition is met or all items in a sequence have been processed.
Loops help developers:
- Automate repetitive tasks
- Process large amounts of data
- Reduce code duplication
- Improve efficiency
- Write cleaner programs
The for Loop
The for loop is used when you know how many times you want to repeat an action or when iterating through a collection.
Syntax
for variable in sequence:
# Code Block
Example:
for i in range(5):
print(i)
Output
0
1
2
3
4
Understanding range()
The range() function generates a sequence of numbers.
Example 1
for i in range(5):
print(i)
Output
0
1
2
3
4
Example 2
for i in range(1,6):
print(i)
Output
1
2
3
4
5
Example 3
Using step value
for i in range(2,11,2):
print(i)
Output
2
4
6
8
10
Iterating Through a String
name = "Python"
for letter in name:
print(letter)
Output
P
y
t
h
o
n
Iterating Through a List
courses = ["Python","Java","React"]
for course in courses:
print(course)
Output
Python
Java
React
Iterating Through a Tuple
numbers = (10,20,30)
for num in numbers:
print(num)
Iterating Through a Dictionary
student = {
"name":"Rahul",
"Age":21,
"City":"Jaipur"
}
for key,value in student.items():
print(key,value)
Output
Name Rahul
Age 21
City Jaipur
The while Loop
The while loop executes as long as a condition remains True.
Syntax
while condition:
# Code
Example
count = 1
while count <= 5:
print(count)
count += 1
Output
1
2
3
4
5
Infinite Loops
If the condition never becomes False, the loop runs forever.
Example
while True:
print("Welcome")
This creates an infinite loop.
Always ensure the loop condition eventually becomes False.
Nested Loops
A loop inside another loop is called a nested loop.
Example
for i in range(3):
for j in range(2):
print(i,j)
Output
0 0
0 1
1 0
1 1
2 0
2 1
Nested loops are commonly used for:
- Matrix operations
- Pattern printing
- Table generation
- Game development
Loop Control Statements
break
Stops the loop immediately.
Example
for i in range(10):
if i == 5:
break
print(i)
Output
0
1
2
3
4
continue
Skips the current iteration.
Example
for i in range(6):
if i == 3:
continue
print(i)
Output
0
1
2
4
5
pass
Acts as a placeholder.
Example
for i in range(5):
pass
Useful when writing code that will be completed later.
Real-World Example 1: Multiplication Table
number = int(input("Enter Number: "))
for i in range(1,11):
print(f"{number} x {i} = {number*i}")
Real-World Example 2: Attendance System
students = ["Rahul","Amit","Priya","Riya"]
for student in students:
print(f"Attendance Marked for {student}")
Real-World Example 3: Password Validation
password = ""
while password != "Python123":
password = input("Enter Password: ")
print("Login Successful")
Real-World Example 4: Shopping Cart
cart = [500,1200,850,600]
total = 0
for item in cart:
total += item
print("Total Bill =",total)
Output
Total Bill = 3150
Common Mistakes
Forgetting to Update the Condition
count = 1
while count <= 5:
print(count)
This creates an infinite loop because count never changes.
Correct
count += 1
Incorrect Indentation
for i in range(5):
print(i)
Python raises an IndentationError.
Wrong range()
range(5)
Starts from 0, not 1.
If you want 1–5
range(1,6)
Best Practices
- Use
forloops when iterating over collections. - Use
whileloops when the number of iterations is unknown. - Avoid infinite loops.
- Use meaningful variable names.
- Keep loops simple.
- Avoid unnecessary nested loops.
- Use
breakandcontinueonly when necessary.
Key Takeaways
- Loops automate repetitive tasks.
forloops iterate over sequences.whileloops execute while a condition is True.range()generates sequences of numbers.- Nested loops allow repeated processing within loops.
breakexits a loop immediately.continueskips the current iteration.passacts as a placeholder.- Loops are essential in automation, AI, web development, and data processing.



