Sitemap

Python - for loop

Aug 30, 2022

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects.

Press enter or click to view image in full size

# Program to find the sum of all numbers stored in a list
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+ val

print(“The sum is”, sum)

Get Mayuresh shewale’s stories in your inbox

Join Medium for free to get updates from this writer.

Output :- The sum is 48

Range

For loops can be used in tandem with Python’s range() function to iterate through each number in a specified range

for x in range(5, 10):
print(x)
5
6
7
8
9

Note that Python doesn’t include the maximum value of a range in the range count

for loop with else

digits = [0, 1, 5]

for i in digits:
print(i)
else:
print(“No items left.”)

Output :-

0
1
5
No items left.

--

--