What is a for loop?
A for loop is a type of loop that allows you to iterate over a sequence (such as a list, tuple, or string) or another iterable object.
The syntax of a for loop in Python is:
for item in sequence:
# code to be executed
Here, item
is a variable that takes on the value of each element in sequence
on each iteration of the loop. The sequence
can be any iterable object, such as a list, tuple, string, or even a range.
Using the break
and continue
statements
You can use the break
and continue
statements within a for loop to control the flow of execution.
The break
statement
The break
statement is used to exit a loop early. For example:
# Find the first even number in a list
numbers = [1, 3, 7, 11, 12, 15]
for number in numbers:
if number % 2 == 0:
print(number)
break
Output:
12
The continue
statement
The continue
statement is used to skip the rest of the current iteration and move on to the next one. For example:
# Print the odd numbers in a list
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number % 2 == 0:
continue
print(number)
Examples of for loops
Here are some examples of for loops in Python:
Loop through a list
# Print the elements of a list
fruits = ['apple', 'banana', 'mango']
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
Loop through a tuple
# Print the elements of a tuple
fruits = ('apple', 'banana', 'mango')
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
Loop through a string
# Print each character of a string
string = "Hello"
for character in string:
print(character)
output:
H
e
l
l
o
Loop through a range
# Print the numbers from 1 to 5
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
You can also specify a step size by including the third argument in the range function:
# Print the even numbers from 1 to 10
for i in range(1, 11, 2):
print(i)
Output:
1
3
5
7
9
Using the range function with a for loop
The range function is often used in conjunction with a for loop to repeat a block of code a certain number of times. For example:
# Print the numbers from 1 to 5
for i in range(5):
print(i+1)
Output:
1
2
3
4
5
Looping through a list of lists
You can use a for loop to iterate over a list of lists:
# Print the elements of a list of lists
fruits = [['apple', 'banana', 'mango'], ['orange', 'strawberry', 'grape']]
for fruit_list in fruits:
for fruit in fruit_list:
print(fruit)
Output:
apple
banana
mango
orange
strawberry
grape
Using the enumerate
function with a for loop
The enumerate
function is often used with a for loop to iterate over a list and obtain the index of each element. The syntax is:
for i, item in enumerate(sequence):
- pybase64 encode and decode Messages using Python - June 6, 2023
- Different Data Types in Dart - June 6, 2023
- What is flutter and dart and the difference - June 4, 2023