Python For Loops
A for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and perform a certain action for each item in the sequence. For loops are useful when you want to repeat a block of code a fixed number of times or iterate over a collection of items.
Syntax
The syntax of a for loop in Python is as follows:
for item in sequence:
# Execute these statements
In this syntax, item
is a variable that will take on the value of each item in thesequence
in each iteration of the loop.
Example
Here's an example of a for loop that iterates over a list of numbers and prints each number:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
This loop will iterate over the list numbers
and print each number on a new line.
Range Function
The range()
function is often used with for loops to generate a sequence of numbers. For example, to iterate over numbers from 0 to 4:
for i in range(5):
print(i)
The range()
function generates a sequence of numbers from 0 to the specified number (exclusive), so range(5)
generates 0, 1, 2, 3, 4.
Conclusion
For loops are a fundamental part of Python programming, allowing you to iterate over sequences and perform actions for each item in the sequence. By understanding how to use for loops, you can write more efficient and expressive Python code.