Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
forloop
loops

How do you execute a simple for loop in Python?

Educative Answers Team

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.

svg viewer
for-loop

Syntax in Python

svg viewer

Flow Diagram

svg viewer
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.

RELATED TAGS

python
forloop
loops
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring