Skip to main content
Practice

How to Perform Iterations Based on Conditions in Python

In programming, a loop is used to perform the same task repeatedly.

Loops iterate over a series of items, such as lists, tuples, or strings, performing the same task for each item.

These lists, tuples, strings, etc., are referred to as sequences, and each item in a sequence is called 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:

Structure of a for Loop
for element in sequence:
code_to_repeat

<br />

Each item in the sequence is sequentially assigned to the variable `element`, and the `code_to_repeat` is executed.

In loops, a colon (`:`) must follow the sequence, 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.