Using for Loops to repeat code in Python
What is a for Loop?
A for
loop in Python is a powerful construct that allows you to iterate over a sequence— such as a list, tuple, dictionary, set, or string— and execute a block of code multiple times based on the items in that sequence. This is exceptionally useful for tasks that require repetitive actions on each element within a collection.
Basic Syntax:
for element in sequence:
# Code to be executed
for Loop Examples and Use Cases
It's easier to grasp the concept of for
loops with practical examples. Here’s how you can use them in different scenarios:
Iterating Over a List: If you have a list of items and need to process each item individually, for
loops are your go-to option.
Try running the code example below:
In this example, the loop will iterate over each fruit in the fruits
list and print it. This is an effective way to handle elements in a collection without writing repetitive code for each item.
Using Range Function: Another common scenario is repeating code a specific number of times which can be efficiently done using the range()
function.
This loop will print the statement "This will be printed 5 times" exactly five times. It’s a simplified way to control the number of iterations you need.
Playing with Dictionaries
Python loops, particularly for
loops, shine when working with dictionaries
. Here’s how you can loop through the keys and values:
This will output each key-value pair in the dictionary, which is an efficient way to access and manipulate dictionary elements.
Repeating code in Python using for
loops is both powerful and simple, making your code more readable and maintainable. You can iterate over various data structures such as lists, tuples, and dictionaries, or simply repeat an action using the range()
function. As you become more comfortable with for
loops, you'll find them indispensable in solving many programming challenges.
Enki provides a personalized learning experience, particularly for beginners diving into the world of Python. Our highly interactive course features an AI mentor to guide you through exercises and give feedback on your code, so you’re never stuck.
The Enki Python Course covers everything from basic syntax to more complex topics, making it a comprehensive starting point for web dev in Python.