- Aliases
- and operator
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- datetime module
- Dictionaries
- enum
- enumerate() function
- Equality operator
- False
- Floats
- For loops
- Formatted strings
- Functions
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Less than operator
- Less than or equal to operator
- List append() method
- List insert() method
- List pop() method
- List sort() method
- Lists
- map() function
- Match statement
- Modules
- None
- not operator
- or operator
- Parameters
- print() function
- range() function
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- String join() method
- String replace() method
- String split() method
- Strings
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
PYTHON
Python For Loop: Syntax and Examples [Python Tutorial]
For loops are control flow statements that allow you to iterate over a sequence or execute a block of code a specific number of times.
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)
Python For Loops with Lists
For loops are great for processing Python lists. For example, you can apply operations to each item in the list, like printing values or modifying data.
colors = ["red", "green", "blue"]
for color in colors:
print(color)
Python For Loops with Dictionaries
For loops are also useful when working with dictionaries. For example, you can iterate over key-value pairs, modify values, or extract data.
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 another 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). In a nested loop, 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
For and while loops are the two kinds of Python loops. Both types of loops 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 you're 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 allows you to exit a loop early when a specific condition becomes true. This makes break
great for exiting a loop before it completed 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 certain 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}")
Python Pass For Loops
You can also add a pass statement to serve as a placeholder within your loop. For example, you can use the pass
keyword to structure your loop while finishing its implementation at a later stage.
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number % 2 == 0:
pass # Placeholder for future logic
else:
print(f"Odd number: {number}")
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 by using the reversed()
Python function.
for i in reversed(range(5)):
print(i)
Another option is creating 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)
Run 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 performing CPU-intensive 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.