Table of Contents | |
There are two types of loop: Python for Loop and Python while Loop.
What is a for
loop in Python?
Python for loop allows you to repeat a block of code a fixed number of times. It works by going through a group of items (like a list of numbers or words) one by one and performing the same actions on each item in the group. This makes it a powerful tool for automating repetitive tasks and working with large amounts of data. Here’s the basic example:
Python for
Loop Example
Imagine you have a list of your favorite fruits. Let’s say you want to tell someone that you like to eat each one of these fruits. You could do it the long way by writing out each sentence one by one:
print("I like to eat apple")
print("I like to eat banana")
print("I like to eat orange")
This works, but what if you had 10 fruits or 20? Writing out each line would take a lot of time and is inefficient.
Now, let’s look at a better way to do this using a Python for loop. Here’s the code:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print("I like to eat", fruit)
This code does the same thing as the previous example, but it’s much shorter and easier to write.
Code Explanation
- Line 1: Creates a list called
fruits
to store fruit names. - Line 2: Starts the loop, passing each word from
fruits
and assigning it to thefruit
variable with each loop repetition. The loop will repeat thrice because three fruits are in the list. - Line 3: The print() function prints the fruit name with each repetition.
Output
I like to eat apple
I like to eat banana
I like to eat orange
The benefit of using a for loop here is that it saves time and makes your code cleaner and easier to read. Instead of writing out each sentence manually, you let Python handle the repetition.
Example
for i in range(1, 11):
print(i)
Code Explanation
- for: This keyword tells Python you’re starting a loop.
- i: This is a variable. It starts at 1 and takes on each value in the sequence as the loop runs. You can name this variable anything you like.
- in: This keyword links the variable
i
to the sequence you’ll loop through. - range(1, 11): This function generates a sequence of numbers from 1 up to, but not including, 11.
- print(i): Each time the loop runs, it prints the current value of
i
.
Output
1
2
3
4
5
6
7
8
9
10
How Python for Loop Works
Here’s how a for loop in Python works step-by-step:
Loop Structure
for item in something_to_loop_over:
# Code to repeat on each item
- Initialization: The loop starts by taking the first
item
from the thing you’re repeating over (something_to_loop_over
, like a list or string). - Body Execution: The code inside the loop’s body (indented block) runs for each
item
in the list. - Iteration: The loop goes back and takes the next
item
from the list. - Repeat: Steps 2 and 3 repeat for each remaining
item
. - Completion: When there are no more
items
left in the list, the loop finishes.
Using else
with Python for Loops
You can add an else clause to a for loop. This else part runs after the loop finishes only if the loop ended normally (meaning it didn’t hit a break statement). Here’s an example:
Example
names = ["Alice", "Bob", "Eve"]
search_name = "David"
for name in names:
if name == search_name:
print(search_name, "found!")
break # Stops loop if name is found
else:
print(search_name, "not found")
Code Explanation
- Line 1: Creates our list of
names
. - Line 2: The
name
we want to find. - Line 4: Begins the loop over our
names
list. - Line 5: Checks each
name
to see if it matches. - Line 7:
break
immediately stops the loop. - Line 8: Executes if David was not found in the list.
Output
David not found
Using break
with Python for Loops
A break statement inside a for loop lets you immediately stop the loop, even if it hasn’t finished going through all the items. Here’s the basic example:
Example
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number % 2 == 0: # Check if number is even
print(number, "is even")
break # Stop as soon as an even number is found
Code Explanation
- Line 1: Creates our list of
numbers
. - Line 2: Starts looping through the list.
- Line 3: Checks if the current
number
is divisible by 2 (even). - Line 5: If an even number is found, exits the loop.
Output
2 is even
Using continue
with Python for Loops
The continue statement in a for loop lets you skip the rest of the current iteration and jump to the next one. This is useful when you want to do something for most items in a list but must ignore certain ones based on a condition. Here’s an example:
Example
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number % 2 == 0: # Skip even numbers
continue
print(number) # Print only odd numbers
Code Explanation
- Line 1: Creates our
numbers
list. - Line 2 Starts the loop.
- Line 3:
continue
: If the currentnumber
is even, skip to the next one. - Line 5: Only reached if the
number
is odd.
Output
1
3
5
Using pass
with Python for Loops
The pass statement in Python is essentially a placeholder. Inside a for loop, it means “do nothing for this iteration.” This is often used when you know you need a loop but are not ready to fill in the actual code yet. Here’s an example:
Example
cities = ["London", "Paris", "Tokyo"]
for city in cities:
# Let's pretend we'll write code to process city data later
pass
Code Explanation
- Line 1: Creates a list of
cities
. - Line 2: Begins looping through the
cities
. - line 4: A placeholder indicating we intend to add code to work with each
city
later. For now, the loop iterates without doing anything.
Nested for Loops in Python
Nested for loops mean putting a for loop inside another for loop. This is great when you need to work with combinations of things, like rows and columns in a table. Here’s the basic example:
Example
for x in range(1, 4): # Rows
for y in range(3): # Columns
print("*", end=" ")
print() # Go to a new line after each row
Code Explanation
- Line 1: Outer loop represents rows (runs 3 times).
- Line 2: Inner loop represents columns (runs 3 times for each row)
- Line 3: Prints a star with a space for each column.
- Line 4: Moves to a new line after each complete row.
Output
***
***
***
Infinite for Loops
In Python, you can make an infinite for loop using the while keyword with a condition that’s always True. This means the loop will keep running forever (until your program is stopped or runs out of resources).
Example
while True:
print("This loop will run forever!")
Code Explanation
- Line 1: Starts the infinite loop.
- Line 2: Prints a message repeatedly, demonstrating the never-ending nature of the loop.
Note: Use infinite loops carefully! They’re usually best with a break statement inside to stop the loop when a condition is met; otherwise, your program might run forever.