Looping is a fundamental concept in programming that allows you to execute a block of code repeatedly. Instead of writing the same code over and over, you can use a loop to perform an action multiple times. This makes your code more efficient, less repetitive, and easier to read. Python has two primary types of loops: the for loop and the while loop.
1. The for Loop
A for loop is used for iterating over a sequence. This means it runs once for each item in an ordered collection, such as a list, a tuple, a string, or a range of numbers.
- Use Case: You use a for loop when you know how many times you want the loop to run—specifically, once for every item in your collection.
Python
# --- for loop with a list ---
fruits = ["apple", "banana", "cherry"]
print("Iterating over a list:")
for fruit in fruits:
print(f"- {fruit}")
# --- for loop with a string ---
print("\nIterating over a string:")
for letter in "Python":
print(letter, end=" ") # Output: P y t h o n
print()
# --- for loop with range() ---
# This is used to repeat an action a specific number of times.
print("\nIterating with range():")
for i in range(5): # Loop from 0 up to (but not including) 5
print(f"Loop number {i}")
2. The while Loop
A while loop repeats a block of code as long as a certain condition is true. It's used when you don't know in advance how many times you need to loop.
- Use Case: You use a while loop when you want the loop to continue until a specific condition is met or a certain state is reached. For example, running a game until the player quits, or processing items until a list is empty.
Python
# --- while loop example ---
# This loop will continue as long as 'count' is less than 5.
count = 0
print("A while loop counting up:")
while count < 5:
print(f"Count is: {count}")
count += 1 # It's crucial to have a way to make the condition False eventually, or you'll have an infinite loop.
print("Loop finished.")
3. Loop Control Statements
These are special keywords that allow you to change the way a loop executes from within the loop.
break
The break statement exits the loop immediately, regardless of the loop's condition.
- Use Case: When you find the item you're looking for and don't need to continue searching, or when a certain error condition is met.
Python
# --- break example ---
# Find the first number divisible by 7
numbers = [2, 13, 21, 30, 49]
print("\nFinding the first number divisible by 7:")
for num in numbers:
if num % 7 == 0:
print(f"Found it! The number is {num}.")
break # Exit the loop immediately
print(f"Checking {num}...")
continue
The continue statement skips the rest of the current iteration and moves on to the next one.
- Use Case: When you want to ignore certain items in a sequence but continue processing the rest.
Python
# --- continue example ---
# Print all numbers except the multiples of 3
print("\nPrinting numbers, skipping multiples of 3:")
for i in range(10):
if i % 3 == 0:
continue # Skip the rest of this iteration
print(i, end=" ") # This line is skipped when i is 0, 3, 6, 9
print()
The else Clause in Loops
Python loops can have an else clause that is executed only if the loop completes without being terminated by a break statement.
- Use Case: To run a piece of code only when a search is unsuccessful (i.e., the break was never triggered).
Python
# --- else clause example ---
# Search for an item in a list
my_list = [1, 2, 3, 4, 5]
item_to_find = 7
print(f"\nSearching for {item_to_find} in {my_list}:")
for item in my_list:
if item == item_to_find:
print("Item found!")
break
else: # This only runs if the loop finishes without a 'break'
print("Item was not found in the list.")
4. Functions and Methods Used with Loops
Loops themselves don't have methods, but they are often used with functions and methods that make them more powerful.
enumerate()
This function is used with for loops to get both the index and the value of each item in a sequence.
- Use Case: When you need to know the position of an item as you are iterating over it.
Python
# --- enumerate() example ---
fruits = ["apple", "banana", "cherry"]
print("\nUsing enumerate() to get index and value:")
for index, fruit in enumerate(fruits):
print(f"Item at index {index} is {fruit}")