How do you execute a simple for loop in Python?

In Python, a for-loop iterates over the members of a sequence (that is either a list, a tuple, a dictionary, a set, or a string) using an iterating variable which keeps track of the current item in the sequence. This allows a piece of code to be executed repeatedly for each member of the sequence.

The for-loop does not require an indexing variable to be set beforehand.

for-loop
for-loop

Syntax in Python

svg viewer

Flow Diagram

Flow Diagram
Flow Diagram

Example

This code will find the sum of all the numbers stored in a list using a for-loop in Python.

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)

The loop in the above code will run nine times as it iterates over the list and adds each item to the previously calculated sum for each iteration.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved