Loops in Python allow you to execute a block of code multiple times. They are a fundamental programming concept used to iterate over data structures or repeat tasks until a specific condition is met.
we’ll cover:
- What are loops in Python?
- Types of loops.
- Examples of each type of loop.
What are Loops?
Loops execute a block of code repeatedly as long as a condition is true. They are especially useful when working with repetitive tasks or iterating through data structures like lists, dictionaries, or strings.
Types of Loops in Python
Python provides two main types of loops:
for
loop: Used for iterating over a sequence (e.g., list, tuple, string).while
loop: Repeats a block of code as long as a condition is true.
1. for
Loop
The for
loop iterates over elements in a sequence (e.g., list, string, or range).
Syntax:
for item in sequence: # Code to execute
Example: Loop through a list
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
Output:
apple banana cherry
Example: Using range()
The range()
function generates a sequence of numbers.
for i in range(1, 6): print(i)
Output:
1 2 3 4 5
2. while
Loop
The while
loop continues executing as long as its condition is True
.
Syntax:
while condition: # Code to execute
Example: Countdown
count = 5 while count > 0: print(count) count -= 1 # Decrease the count by 1
Output:
5 4 3 2 1
3. Nested Loops
A loop inside another loop is called a nested loop.
Example: Multiplication Table
for i in range(1, 4): for j in range(1, 4): print(f"{i} x {j} = {i * j}")
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
4. Control Statements in Loops
Python provides control statements to manage the flow of loops:
break
: Exits the loop prematurely.continue
: Skips the rest of the loop’s body for the current iteration.pass
: Does nothing; acts as a placeholder.
break
Example
Exit the loop when a condition is met.
for number in range(1, 6): if number == 3: break print(number)
Output:
1 2
continue
Example
Skip the current iteration and proceed with the next.
for number in range(1, 6): if number == 3: continue print(number)
Output:
1 2 4 5
pass
Example
Do nothing in the loop (used as a placeholder).
for number in range(1, 6): if number == 3: pass else: print(number)
Output:
1 2 4 5
5. Iterating Over Data Structures
Strings
You can iterate over each character in a string.
word = "Python" for char in word: print(char)
Output:
P y t h o n
Lists
numbers = [10, 20, 30] for num in numbers: print(num)
Output:
10 20 30
Dictionaries
Iterate through keys and values.
person = {"name": "Alice", "age": 25} for key, value in person.items(): print(f"{key}: {value}")
Output:
name: Alice age: 25
6. Else with Loops
Both for
and while
loops can have an else
clause that executes after the loop finishes.
Example: Using else
with a for
Loop
for number in range(1, 4): print(number) else: print("Loop completed.")
Output:
1 2 3 Loop completed.
Example: Using else
with a while
Loop
count = 3 while count > 0: print(count) count -= 1 else: print("Countdown finished.")
Output:
3 2 1 Countdown finished.
Common Mistakes with Loops
-
Infinite Loops: Forgetting to update the condition in a
while
loop can result in an infinite loop.count = 3while count > 0: print(count) # No decrement leads to infinite loop!
-
Misusing
break
andcontinue
: Understand when to exit or skip iterations carefully. -
Improper Indentation: Python relies on indentation to define loop bodies.