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:
0
1
2
3
4
"""
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:
apple
banana
cherry
"""
Looping Through a Tuple
fruits_tuple = ("apple", "banana", "cherry")
for fruit in fruits_tuple:
print(fruit)
"""
Output:
apple
banana
cherry
"""
Looping Through a Set
fruits_set = {"apple", "banana", "cherry"}
for fruit in fruits_set:
print(fruit)
"""
Output:
apple
banana
cherry
"""
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 red
banana is yellow
cherry is red
"""
- With
keys()
for key in fruits_dict.keys():
print(f"Fruit key: {key}")
"""
Output:
Fruit key: apple
Fruit key: banana
Fruit key: cherry
"""
- With
values()
for value in fruits_dict.values():
print(f"Fruit value: {value}")
"""
Output:
Fruit Values: red
Fruit Values: yellow
Fruit 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 = 0
while index < len(fruits):
item = fruits[index]
print(f"At index {index} is {item}")
index += 1
"""
Output:
At index 0 is apple
At index 1 is banana
At 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 list
index = 0 # Initialize index
while index < len(keys):
key = keys[index]
print(f"index: {index}, key: {key}")
index += 1
"""
Output:
index: 0, key: apple
index: 1, key: banana
index: 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:
apple
Skipping banana...
cherry
"""
Else Example
fruits = ["apple", "banana", "cherry"]
for item in fruits:
if item == "watermelon":
print("Found a watermelon!")
break
else:
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!