- Alias
- and operator
- append()
- Booleans
- Classes
- Code block
- Comments
- Conditions
- Console
- datetime module
- Dictionaries
- enum
- enumerate() function
- Equality operator
- False
- Float
- For loop
- Formatted strings
- Functions
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Index
- Indices
- Inequality operator
- insert()
- Integer
- Less than operator
- Less than or equal to operator
- List sort() method
- Lists
- map() function
- Match statement
- Modules
- None
- or operator
- Parameter
- pop()
- print() function
- range() function
- Regular expressions
- requests Library
- Return
- round() function
- Sets
- String
- String join() method
- String replace() method
- String split() method
- The not operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loop
PYTHON
Python For Loop: Syntax and Examples [Python Tutorial]
For loops are control flow statements that allow you to iterate over a sequence, such as a list, tuple, dictionary, set, or string. With a for loop, you can execute a block of code a specific number of times or work with collections of data.
How to Use the For Loop in Python
The for loop is easy to understand, even for beginners. Compared to programming languages like Java or JavaScript, Python 3 offers a simpler for loop syntax.
for item in sequence:
# Code to execute for each item
for
: The keyword that starts the for loop statement.item
: The loop variable that takes the current item's value in the sequence during each iteration of the loop.in
: The keyword that links the variable to the sequence.sequence
: The array, tuple, dictionary, set, string, or other iterable data types to iterate over.
Using indentation, the block of code after the for loop statement executes as long as there are items in the sequence.
Basic Usage
Here’s a simple Python for loop example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(f"Number: {number}")
In this example, the loop iterates over the list of numbers with a starting value of 1
. Each iteration assigns the current value from the sequence of numbers to number
. The function call in the code block prints each number in the list.
When to Use the For Loop in Python
Python Range For Loop
range()
is a built-in function that creates a list of numbers starting at 0
and stopping before a specified integer. This makes the range
function ideal for creating Python for loops with index variables.
for i in range(5):
print(i)
In this example, the loop runs five times and increments i
from the starting value 0
to 4
.
Python For Loops with Lists
You can apply operations to each item in a list, from printing values to modifying data.
colors = ["red", "green", "blue"]
for color in colors:
print(color)
Iterating over Python Dictionaries
You can iterate over key-value pairs, modify values, or extract data when working with dictionaries.
user_info = {"name": "Alice", "age": 25}
for key, value in user_info.items():
print(f"{key}: {value}")
Examples of Python Programs With For Loops
E-commerce Platforms
An e-commerce app might use a for loop to calculate discounts. During a sale, the app could iterate over the list of items in the cart and apply a 10% discount.
cart = [{"item": "Shoes", "price": 50}, {"item": "Shirt", "price": 30}]
for product in cart:
product['price'] = product['price'] * 0.9 # Apply 10% discount
print(f"Discounted price for {product['item']}: ${product['price']}")
Fitness Tracking Apps
A fitness tracking app might use a for loop to calculate the total calories burned across multiple exercises.
exercises = [{"exercise": "Running", "calories": 300}, {"exercise": "Cycling", "calories": 250}]
total_calories = 0
for exercise in exercises:
total_calories += exercise["calories"]
print(f"Total calories burned: {total_calories}")
Machine Learning Model Training
A numpy
or pandas
-based data science application might use a for loop to iterate over datasets. For instance, a for loop can evaluate performance scores and check if they meet a certain threshold.
import numpy as np
# Example performance scores
scores = np.array([0.85, 0.88, 0.90, 0.92, 0.95])
for score in scores:
if score < 0.90:
print(f"Model performance below threshold: {score}")
else:
print(f"Model meets performance standards: {score}")
Learn More About For Loops in Python Programming
Nested For Loops in Python
You can also create a loop within a loop, a process called nesting. Python nested for loops allow you to iterate over multi-dimensional data structures, like lists of lists (e.g., matrices). The outer loop iterates through each main element (like rows in a matrix). The inner loop processes individual elements within those items (like elements in a matrix's row).
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for item in row:
print(item)
While Loop and For Loop in Python
Both types of loops in Python allow you to repeat code but shine in different situations. For loops are ideal when you know how many times you need to iterate or when working with an iterable object.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}!")
Using a while loop for the same task would be more cumbersome. You would have to update the index variable and check when to stop the loop.
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(f"I love {fruits[i]}!")
i += 1
Python while loops are perfect for when the number of iterations is unclear and depends on a condition. In such scenarios, you can keep a while loop running as long as the condition is true (i.e., returns the boolean value True
).
user_input = ""
while user_input != "quit":
user_input = input("Enter a command (type 'quit' to exit): ")
Creating a Dictionary with a For Loop in Python
You can create dictionaries during a program's runtime using a for loop. This is particularly useful for generating a dictionary from two lists (keys and values).
keys = ["name", "age", "country"]
values = ["John", 30, "USA"]
# Creating a dictionary from two lists
employee_dict = {k: v for k, v in zip(keys, values)}
print(employee_dict)
Python Break For Loops
A break statement lets you exit a loop early when a specific condition becomes true. This makes break
great for leaving a loop before it completes all iterations.
commands = ["start", "pause", "quit", "restart"]
for command in commands:
if command == "quit":
break # Exit when 'quit' is encountered
print(f"Processing {command}")
Python Continue For Loops
A continue statement skips the current iteration and moves directly to the next one. This makes continue
ideal for skipping some elements in a loop.
data_points = [1, 2, -1, 4, -5, 6]
for data in data_points:
if data < 0: # Skip negative numbers
continue
print(f"Processing data point: {data}")
Using For Loops with Indexing in Python
Sometimes, you need both the index and the value while iterating through a list. You can achieve this with the enumerate()
function, which provides both the index and the item during iteration.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Python Reverse For Loop
You can loop over a sequence in reverse order using the reversed()
Python function.
for i in reversed(range(5)):
print(i)
Another option is to create a for loop with Python’s range()
function and its start
, stop
, and step
parameters.
for i in range(4, -1, -1): # Reverse Python for loop with range()
print(i)
Running For Loops in Parallel in Python
Python has libraries like concurrent.futures
and multiprocessing
that allow you to run multiple for loops in parallel. This is especially useful when dealing with CPU-heavy tasks.
from concurrent.futures import ThreadPoolExecutor
def process_item(item):
return item ** 2
items = [1, 2, 3, 4, 5]
with ThreadPoolExecutor() as executor:
results = list(executor.map(process_item, items))
print(results)
Python Add Time Delays in For Loops
You can use the time.sleep()
function to add a delay of a specific amount of time between loop iterations. This can be useful in applications like countdown timers or when waiting for responses.
import time
for i in range(5):
print(f"Iteration {i}")
time.sleep(1) # Pause for 1 second between iterations
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.