A for loop is a control structure that allows you to iterate over a sequence (such as a list, tuple, or string) or an iterable object (such as a dictionary, set, or file), and execute a block of code for each element in the sequence. Here is an example of a for loop in Python:
# Iterate over a list of numbers and print each number
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
# Output:
# 1
# 2
# 3
# 4
# 5
You can also use the range() function to generate a sequence of numbers and iterate over them using a for loop:
# Iterate over a range of numbers and print each number
for i in range(1, 6):
print(i)
# Output:
# 1
# 2
# 3
# 4
# 5
You can use the enumerate() function to iterate over a list and get the index and value of each element at the same time:
# Iterate over a list of strings and print the index and value of each element
words = ["cat", "dog", "bird"]
for i, word in enumerate(words):
print(f"{i}: {word}")
# Output:
# 0: cat
# 1: dog
# 2: bird
You can use the break statement to exit a for loop prematurely, and the continue statement to skip the rest of the current iteration and move on to the next one.
# Iterate over a list of numbers and exit the loop when the number is 3
for number in [1, 2, 3, 4, 5]:
if number == 3:
break
print(number)
# Output:
# 1
# 2
# Iterate over a list of numbers and skip the rest of the current iteration when the number is 3
for number in [1, 2, 3, 4, 5]:
if number == 3:
continue
print(number)
# Output:
# 1
# 2
# 4
# 5
You can also nest for loops, to iterate over multiple sequences or iterables at the same time:
# Iterate over two lists and print the combinations of their elements
colors = ["red", "green", "blue"]
shapes = ["circle", "square", "triangle"]
for color in colors:
for shape in shapes:
print(f"{color} {shape}")
# Output:
# red circle
# red square
# red triangle
# green circle
# green square
# green triangle
# blue circle
# blue square
# blue triangle
For more information please visit python.org
This article is created based on experience but If you discover any corrections or enhancements, please write a comment in the comment section or email us at contribute@devopsforu.com. You can also reach out to us from Contact-Us Page.
Follow us on LinkedIn for updates!