Understanding For Loops in Python
Python's for
loop is a powerful tool for iterating over sequences, such as lists, tuples, strings, and more. It allows you to execute a block of code repeatedly, making it a versatile construct for a wide range of programming tasks.
What is a For Loop?
A for
loop in Python is used to iterate over a sequence (such as a list, tuple, string, etc.) and execute a block of code for each item in the sequence. The general syntax for a for
loop in Python is:
for item in sequence:
## code block to be executed
The item
variable represents each element in the sequence
as the loop iterates through it. The code block within the loop will be executed once for each item in the sequence.
Iterating Over Sequences
The most common use of for
loops in Python is to iterate over sequences, such as lists, tuples, and strings. Here's an example of iterating over a list of numbers:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
This will output:
1
2
3
4
5
You can also use for
loops to iterate over strings, where each iteration will assign the current character to the loop variable:
greeting = "Hello, LabEx!"
for char in greeting:
print(char)
This will output:
H
e
l
l
o
,
L
a
b
E
x
!
Range Function
The range()
function is often used in conjunction with for
loops to iterate over a sequence of numbers. The range()
function generates a sequence of numbers, which can be used in a for
loop. Here's an example:
for i in range(5):
print(i)
This will output:
0
1
2
3
4
The range()
function can also be used to specify a starting and ending point, as well as a step size:
for i in range(2, 10, 2):
print(i)
This will output:
2
4
6
8
By understanding the basics of for
loops in Python, you can now move on to the next section, where we'll explore how to use for
loops to print various patterns.