What is a Python for loop?
A Python for loop is a programming construct that allows you to iterate over a sequence of data and execute a block of code for each item in the sequence. The syntax for a for loop is as follows:
Python
for item in sequence:
code block
The sequence can be any iterable object, such as a list, tuple, string, or dictionary. The code block is executed for each item in the sequence.
Examples:
Python
# Print the contents of a list
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
# Iterate over a string
my_string = "Hello, World!"
for char in my_string:
print(char)
# Iterate over a dictionary
my_dictionary = {"name": "John Doe", "age": 30}
for key in my_dictionary:
print(key)
How to use for loops effectively
Here are some tips for using for loops effectively:
Break and continue statements
The break statement is used to terminate a loop prematurely. The continue statement is used to skip the rest of the current iteration of a loop and start the next iteration.
Examples:
Python
# Print the numbers from 1 to 10, but break the loop when the number reaches 5
for i in range(1, 11):
print(i)
if i == 5:
break
# Iterate over a list and skip the rest of the current iteration of the loop if the number is even
my_list = [1, 2, 3, 4, 5]
for number in my_list:
if number % 2 == 0:
continue
print(number)
Conclusion
Python for loops are a powerful tool that can be used to iterate over a sequence of data and execute a block of code for each item in the sequence. By understanding how to use for loops effectively, you can write more efficient and readable Python code.