Python Essential - Looping Like a Pro
What is a Python Loop?
In Python, loops are essential constructs that allow you to execute a block of code repeatedly. There are different types of loops available, each with its own purpose and usage. Let’s explore how loops work in Python and provide examples of using them with lists, tuples, sets, and dictionaries.
for i in range(5): print(i)
"""Output:01234"""
The for Loop
The for
loop is used to iterate over a sequence of elements such as lists, tuples, sets, or dictionaries. It executes a block of code for each item in the sequence.
Looping Through a List
fruits_list = ["apple", "banana", "cherry"]
for fruit in fruits_list: print(fruit)
"""Output:applebananacherry"""
Looping Through a Tuple
fruits_tuple = ("apple", "banana", "cherry")
for fruit in fruits_tuple: print(fruit)
"""Output:applebananacherry"""
Looping Through a Set
fruits_set = {"apple", "banana", "cherry"}for fruit in fruits_set: print(fruit)
"""Output:applebananacherry"""
Looping Through a Dictionary
fruits_dict = {"apple": "red", "banana": "yellow", "cherry": "red"}
- With
items()
for key, value in fruits_dict.items(): print(f"{key} is {value}")
"""Output:apple is redbanana is yellowcherry is red"""
- With
keys()
for key in fruits_dict.keys(): print(f"Fruit key: {key}")
"""Output:Fruit key: appleFruit key: bananaFruit key: cherry"""
- With
values()
for value in fruits_dict.values(): print(f"Fruit value: {value}")
"""Output:Fruit Values: redFruit Values: yellowFruit Values: red"""
The while Loop
The while
loop in Python repeats a block of code as long as a specified condition remains true. It’s particularly useful when the number of iterations is unknown beforehand.
Basic Example
This code demonstrates the usage of a while loop with both lists and tuples.
fruits = ["apple", "banana", "cherry"]# Uncomment this to see tuple example# fruits = ("apple", "banana", "cherry")
index = 0while index < len(fruits): item = fruits[index] print(f"At index {index} is {item}") index += 1
"""Output:At index 0 is appleAt index 1 is bananaAt index 2 is cherry"""
Dictionary Example
Lets say if you want to loop through a dictionary, there are extra steps to setup first
fruits_dict = {"apple": "red", "banana": "yellow", "cherry": "red"}
keys = list(fruits_dict.keys()) # Get the keys as a listindex = 0 # Initialize indexwhile index < len(keys): key = keys[index] print(f"index: {index}, key: {key}") index += 1
"""Output:index: 0, key: appleindex: 1, key: bananaindex: 2, key: cherry"""
Loop Control Statements
Python provides loop control statements such as break
, continue
, and else
to control the flow of the loop.
Break Example
fruits = ["apple", "banana", "cherry"]
for item in fruits: if item == "banana": print("Found banana! Exiting loop.") break"""Output:Found banana! Exiting loop."""
Continue Example
fruits = ["apple", "banana", "cherry"]
for item in fruits: if item == "banana": print("Skipping banana...") continue print(item)"""Output:appleSkipping banana...cherry"""
Else Example
fruits = ["apple", "banana", "cherry"]
for item in fruits: if item == "watermelon": print("Found a watermelon!") breakelse: print("Watermelon is not found.")
"""Output:Watermelon is not found."""
Resources
Python Docs - 5.6 Loop Techniques
Thank you
Thank you for your time and for reading this!