How to Perform Iterations Based on Conditions in Python
In programming, a loop
is used to perform the same task multiple times.
Loops iterate over a series of items, such as lists, tuples, or strings, performing the same task for each item.
These lists, tuples, and strings are called sequences, and each item in a sequence
is known as an element
.
Structure of a for Loop
A for loop starts with the for
keyword and specifies a variable
that represents each item in the sequence
to be iterated over as follows:
python title="Structure of a for Loop"
for element in sequence:
code_to_repeat
Each item in the sequence is assigned to the variable element
one by one, and the code_to_repeat
is executed each time.
In a for loop, a colon (:
) must be placed after the loop statement, and the code_to_repeat
must be indented.
The following for
loop example assigns each element of the numbers
list, a sequence of numbers, to the n
variable in turn and prints n
.
python title="for Loop Example"
numbers = [1, 2, 3, 4, 5]
# Assign each element of the numbers list to the variable n in turn
for n in numbers:
print(n) # Print the variable n
# 1, 2, 3, 4, 5 will be printed on separate lines
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.