Loops are one of the most fundamental concepts in programming. They allow you to repeat a block of code multiple times without having to write it over and over again. Let's dive deep into Python's two main types of loops: for loops and while loops.
Table of Contents
Why Do We Need Loops?
The for Loop
The while Loop
Loop Control Statements
Nested Loops
Common Patterns and Best Practices
1. Why Do We Need Loops?
Imagine you want to print "Hello" 10 times. Without loops, you'd have to write:
print("Hello")
print("Hello")
print("Hello")
That's tedious and impractical! Loops solve this problem elegantly:
for i in range(10):
print("Hello")
2. The for Loop
The for loop is used when you know in advance how many times you want to repeat something, or when you want to iterate through a collection of items.
Basic Syntax
for variable in sequence:
Example 1: Looping Through a Range
The range() function generates a sequence of numbers:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Note: range(5) generates numbers from 0 to 4 (not including 5).
Example 2: Custom Range
You can specify start, stop, and step values:
for i in range(2, 10, 2):
print(i)
Output:
2
4
6
8
Example 3: Looping Through a List
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
print(f"I love {fruit}!")
Output:
I love apple!
I love banana!
I love cherry!
I love date!
Example 4: Looping Through a String
Strings are iterable, so you can loop through each character:
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
Example 5: Using enumerate() for Index and Value
When you need both the index and the value:
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"Index {index}: {color}")
Output:
Index 0: red
Index 1: green
Index 2: blue
Example 6: Looping Through a Dictionary
student = {"name": "Alice", "age": 20, "grade": "A"}
for key in student:
print(key)
for value in student.values():
print(value)
for key, value in student.items():
print(f"{key}: {value}")
![]()

3. The while Loop
The while loop continues executing as long as a condition is true. It's useful when you don't know in advance how many iterations you'll need.
Basic Syntax
while condition:
Example 1: Basic While Loop
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
Output:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Warning: Always make sure your condition will eventually become false, or you'll create an infinite loop!
password = ""
while password != "python123":
password = input("Enter the password: ")
if password != "python123":
print("Wrong password, try again!")
print("Access granted!")
Example 3: Infinite Loop (Use with Caution)
Sometimes you want a loop that runs forever until explicitly stopped:
while True:
user_input = input("Type 'quit' to exit: ")
if user_input == "quit":
break
print(f"You typed: {user_input}")
4. Loop Control Statements
These statements give you more control over loop execution.
The break Statement
Exits the loop immediately, regardless of the condition:
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
The continue Statement
Skips the rest of the current iteration and moves to the next one:
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
The else Clause in Loops
Python has a unique feature: loops can have an else clause that executes when the loop completes normally (not interrupted by break):
for i in range(5):
print(i)
else:
print("Loop completed successfully!")
Output:
0
1
2
3
4
Loop completed successfully!
But if the loop is interrupted by break:
for i in range(5):
if i == 3:
break
print(i)
else:
print("This won't print because of break")
Output:
0
1
2
5. Nested Loops
You can place loops inside other loops. This is useful for working with multi-dimensional data or creating patterns.
Example 1: Multiplication Table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")
print()
Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
Example 2: Pattern Printing
for i in range(5):
for j in range(i + 1):
print("*", end="")
print()
Output:
*
**
***
****
*****

6. Common Patterns and Best Practices
Pattern 1: Summing Numbers
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}")
Pattern 2: Finding Maximum Value
numbers = [23, 45, 12, 67, 34]
max_value = numbers[0]
for num in numbers:
if num > max_value:
max_value = num
print(f"Maximum: {max_value}")
Pattern 3: List Comprehension (Advanced For Loop)
A concise way to create lists:
squares = []
for i in range(5):
squares.append(i ** 2)
squares = [i ** 2 for i in range(5)]
print(squares)
Pattern 4: Filtering with Loops
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers)
Best Practices
Choose the right loop type: Use for when iterating over sequences, while when the number of iterations is unknown.
Avoid infinite loops: Always ensure your while loop condition will eventually become false.
Use meaningful variable names: Instead of i, use student, item, etc. when it makes the code clearer.
Keep loops simple: If a loop is getting too complex, consider breaking it into functions.
Be careful with modifying lists during iteration: This can lead to unexpected behavior. Create a copy if needed.
Practice Exercises
Try these to reinforce your learning:
Write a loop that prints all even numbers from 1 to 20.
Create a program that asks the user for numbers until they type "done", then prints the sum.
Print a countdown from 10 to 1, then print "Liftoff!"
Create a pattern of numbers that looks like a right triangle.
Write a loop that finds all numbers divisible by both 3 and 5 between 1 and 100.
Loops are powerful tools that you'll use constantly in Python programming. The more you practice, the more intuitive they'll become. Start with simple examples and gradually work your way up to more complex scenarios!
You just mastered one of the most important building blocks of AI & ML programming!
Ready to put loops (and everything else) into real-world AI projects?
Join our AI and Machine Learning Bootcamp today and go from beginner to job-ready in just 8 Months You’ll build real projects: image classifiers, chatbots, predictive models and lot more
Limited seats | Hands-on | Career support | Live mentorship

Click here to get started