A loop in Python is used to execute a block of code repeatedly. Instead of writing the same code multiple times, we can use a loop to perform the same task efficiently.
For example, if you want to print “Hello Python” five times, you can use a loop instead of writing five separate print statements.
Python mainly provides two types of loops:
for Loop
while Loop
In this tutorial, we will learn the Python for loop with simple examples.
1. Python for Loop Syntax
The basic syntax of a for loop is:
for variable in sequence:
# Code to executeExplanation:
forstarts the loop.variablestores the current item during each iteration.intakes items from a sequence.sequencecan be a list, string, range, or another iterable.The indented code runs for each item.
2. Example: Print Numbers from 1 to 5
Python Code:
for i in range(1, 6):
print(i)Output:
1
2
3
4
5Explanation
range(1, 6)generates numbers from 1 to 5.The ending number
6is not included.ireceives one number at a time.print(i)displays each number.
3. Example: Print a Message 5 Times
for i in range(5):
print("Hello Python")Output:
Hello Python
Hello Python
Hello Python
Hello Python
Hello PythonHere, range(5) generates five values: 0, 1, 2, 3, and 4. Therefore, the message prints five times.
4. Example: Calculate the Sum of Numbers from 1 to 10
total = 0
for i in range(1, 11):
total = total + i
print("Total =", total)Output:
Total = 55Explanation
total = 0initializes the total.The loop generates numbers from 1 to 10.
total = total + iadds each number to the previous total.print()displays the final sum.
For example, the calculation is:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
5. Example: Print Items from a List
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)Output:
Apple
Banana
MangoIn this example, the loop takes each fruit from the list and prints it one by one.
6. Difference Between for Loop and while Loop
| for Loop | while Loop |
|---|---|
| Commonly used to iterate over a sequence. | Repeats while a condition is true. |
Often used with lists and range(). | Often used when repetition depends on a condition. |
Example: for i in range(5): | Example: while i < 5: |
Both loops are useful for automating repetitive tasks in Python.
7. Python Loop Practice Questions
Try solving these questions yourself.
Question 1: Write a Python program to print numbers from 1 to 20.
Question 2: Write a program to print the multiplication table of 5.
Question 3: Write a program to calculate the sum of numbers from 1 to 100.
Question 4: Given the list below, print each student’s name using a for loop.
students = ["Amit", "Rohit", "Priya", "Neha"]Question 5: Write a program to print all even numbers from 2 to 20.
Conclusion
Python loops are essential for programming and automation. They help reduce repetitive code and make programs easier to maintain. Learning for and while loops will help you build practical Python projects and solve real-world problems.
Keep Practicing!

good one.