In this tutorial, you will learn about Python for loops.
A for loop is used to execute a block of code repeatedly for each item in the sequence.
Basic syntax of a for loop:
for item in sequence:
# Code to execute for each item
Example 1: Loop through a list
In the example below, you will get a loop through a list.
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
Output:
applebanana
orange
Example 2: Using range() to loop through a sequence of numbers
for i in range(5):
print(i)
Output:
01
2
3
4
Note: range(5) generates a sequence of numbers from 0 to 4 (5 numbers).
Example 3: Loop through a string
name= "John"
for letter in name:
print(letter)
Output:
Jo
h
n
Example 4: Using else with a for loop
The else clause is optional and will be executed after the loop finishes unless the loop is terminated by a break statement.
for i in range(3):
print(i)
else:
print("Finished!")
Output:
01
2
3
Finished!
Python for loop – Interview Questions
Q 1: What is a for loop in Python?
Q 2: Which sequences can a for loop iterate over?
Q 3: What is the use of range() in a for loop?
Q 4: Can a for loop have an else block?
Q 5: How do you stop a for loop?
Python for loop – Objective Questions (MCQs)
Q1. Which keyword is used to create a for loop in Python?
Q2. What will be the output of the following code?
for i in range(3):
print(i)
Q3. Which function is commonly used with for loops to generate a sequence of numbers?
Q4. What will the following code print?
for x in "PYTHON":
print(x, end=" ")
Q5. Which statement can be used to stop a for loop before it has looped through all the items?