Click for All Topics
A for loop
helps you go through a bunch(sequential) of items one by one, like words in a sentence or numbers in a list, and do something with each item in a quick and easy way.
Syntax:
# General code of for loop
for item in iterable:
# Code block - do something with 'item'
print(item)
Explanation:
A programmer named Jay. He had to perform the same task repeatedly. He learned to use the “for” loop to handle this task in his programming.
In the same way, a “for” loop in programming helps you repeat a set of actions for each item.
Code:
# Using a for loop for Jay's daily task
for day in range(1, 11): # Assuming 10 days for demonstration
print("Day", day, ": Perform the task")
# Output -
# Day 1 : Perform the task
# Day 2 : Perform the task
# Day 3 : Perform the task
# Day 4 : Perform the task
# Day 5 : Perform the task
# Day 6 : Perform the task
# Day 7 : Perform the task
# Day 8 : Perform the task
# Day 9 : Perform the task
# Day 10 : Perform the task
Examples of for loop:
Range() is used to create a sequence of numbers and by default, it starts with 0 but we can change this default value. You tell it where to start, where to end, and how to step(step size).
It is commonly used with a for loop
. It is a versatile function and has many advantages.
💡Note: range(5) means values from 0 to 4 and not 0 to 5.
Example:
# Example of a for loop with range function
for i in range(1, 6):
print("Iteration:", i)
# Output -
# Iteration: 1
# Iteration: 2
# Iteration: 3
# Iteration: 4
# Iteration: 5
Example: for loop with a step size
Step size is a parameter that lets you define the interval between consecutive values in the sequence.
💡Note: range(2,7,3) here 3 is step size which is generally 1 by default.
start = 1 # Starting value
end = 10 # Ending value (inclusive)
step = 2 # Step size
for number in range(start, end + 1, step):
print("Current number:", number)
# Output -
# Current number: 1
# Current number: 3
# Current number: 5
# Current number: 7
# Current number: 9
# Example of a for loop with list.
values = [1, 3, 5, 7, 9]
for number in values:
print("Current number:", number)
# Output -
# Current number: 1
# Current number: 3
# Current number: 5
# Current number: 7
# Current number: 9
fruits = {"apple": 5, "banana": 6, "orange": 6, "grape": 5}
for fruit in fruits.keys():
print("There are fruits",fruit)
# Output -
# There are fruits apple
# There are fruits banana
# There are fruits orange
# There are fruits grape
fruits = {"apple": 5, "banana": 6, "orange": 6, "grape": 5}
for quantity in fruits.values():
print("There are fruits",quantity)
# Output -
# There are fruits 5
# There are fruits 6
# There are fruits 6
# There are fruits 5
fruits = {"apple": 5, "banana": 6, "orange": 6, "grape": 5}
for fruit, quantity in fruits.items():
print(f"There are {fruit} and there quantity are",quantity)
# Output -
# There are apple and there quantity are 5
# There are banana and there quantity are 6
# There are orange and there quantity are 6
# There are grape and there quantity are 5
n="fruits"
for i in n:
print(i)
# Output -
# f
# r
# u
# i
# t
# s
n=(1,2,3,4,6)
for i in n:
print(i)
# Output -
# 1
# 2
# 3
# 4
# 6
💡Note: The else block will not be executed if the loop is stopped by a break statement.
n=(1,2,3,4,6)
for i in n:
print("number in n:",i)
else:
print('numbers over')
# Output -
# number in n: 1
# number in n: 2
# number in n: 3
# number in n: 4
# number in n: 6
# numbers over
A nested for loop is like a tool in programming that’s often used to create interesting patterns using code. Think of it as a way to build shapes or designs using stars, numbers, or other symbols.
Example –
# Nested for loop example
for row in range(1, 4):
for col in range(1, 4):
print("Row:", row, "| Column:", col)
# Output -
# Row: 1 | Column: 1
# Row: 1 | Column: 2
# Row: 1 | Column: 3
# Row: 2 | Column: 1
# Row: 2 | Column: 2
# Row: 2 | Column: 3
# Row: 3 | Column: 1
# Row: 3 | Column: 2
# Row: 3 | Column: 3
💡Note: We cannot use logical and conditional expressions directly with for loop but we can use them inside for loop using if or while.
Exception handling in a for loop
is like having a backup plan for when things don’t go as expected.
numbers = [2, 4, 6, 8, 10, 'twelve']
for num in numbers:
try:
result = 20 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
except TypeError:
print("Invalid type. Expected a number.")
else:
print("20 divided by", num, "is:", result)
finally:
print("Calculation finished for", num)
# Output -
# 20 divided by 2 is: 10.0
# Calculation finished for 2
# 20 divided by 4 is: 5.0
# Calculation finished for 4
# 20 divided by 6 is: 3.3333333333333335
# Calculation finished for 6
# 20 divided by 8 is: 2.5
# Calculation finished for 8
# 20 divided by 10 is: 2.0
# Calculation finished for 10
# Invalid type. Expected a number.
# Calculation finished for twelve
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India