Python Foundation

Loops in Python

01 · Introduction Loops · 1 of 15

What are Loops?

A loop is a way to repeat a block of code multiple times without writing the same code again and again.

In real life we do many repetitive tasks:

  • Checking attendance of 50 students one by one
  • Sending the same message to 100 customers
  • Adding all numbers from 1 to 100

Instead of writing the code 50 or 100 times, we write it once and tell Python to repeat it.

Python has two main types of loops:

  • for loop → used when we know how many times to repeat, or when we want to go through each item in a collection
  • while loop → used when we want to repeat as long as a condition is True

Both are extremely important. You will use them in almost every program, especially when working with lists, tuples, sets and dictionaries.

02 · for Loop Basics Loops · 2 of 15

The for Loop

The for loop is used to iterate over a sequence (list, tuple, string, set, dictionary, or range).

Basic Syntax:

Python
for variable in sequence:
    # code to repeat
    statement 1
    statement 2

How it works step by step:

  1. Python takes the first item from the sequence and stores it in the variable
  2. It runs the indented block of code
  3. Then it takes the next item and repeats the process
  4. This continues until all items are finished

Example 1 – Simple for loop

Python
for i in range(5):
    print("Hello", i)
Output:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4

The loop ran 5 times. Each time the value of i changed from 0 to 4.

Example 2 – Looping through a string

Python
name = "PYTHON"

for letter in name:
    print(letter)
A string is also a sequence of characters. So the loop prints each letter on a new line.
03 · range() Function Loops · 3 of 15

The range() Function

range() is very commonly used with for loops. It generates a sequence of numbers.

Three ways to use range():

Python
# 1. range(stop)           → from 0 to stop-1
for i in range(5):
    print(i)
# Output: 0 1 2 3 4

# 2. range(start, stop)    → from start to stop-1
for i in range(2, 7):
    print(i)
# Output: 2 3 4 5 6

# 3. range(start, stop, step)
for i in range(1, 10, 2):
    print(i)
# Output: 1 3 5 7 9

# Negative step (counting backwards)
for i in range(10, 0, -2):
    print(i)
# Output: 10 8 6 4 2
Important: The stop value is never included. range(5) gives 0,1,2,3,4 (not 5).
04 · while Loop Loops · 4 of 15

The while Loop

The while loop repeats a block of code as long as a condition remains True.

Syntax:

Python
while condition:
    # code to repeat
    statement 1
    statement 2

How it works:

  1. Python checks the condition
  2. If True → runs the block
  3. Goes back and checks the condition again
  4. Continues until the condition becomes False

Example 1 – Counting

Python
count = 1

while count <= 5:
    print("Count is:", count)
    count = count + 1

print("Loop finished")
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Loop finished

When count becomes 6, the condition count <= 5 becomes False and the loop stops.

Example 2 – Taking input until user stops

Python
total = 0

while True:
    num = int(input("Enter a number (0 to stop): "))
    if num == 0:
        break
    total = total + num

print("Total =", total)
This is a common pattern: keep asking the user for input until they enter a special value (here 0).

Warning – Infinite Loop

Python
# Dangerous example (never run this without break)
count = 1
while count <= 5:
    print(count)
    # forgot to increase count → infinite loop
Always make sure the condition will eventually become False, otherwise the loop will run forever.
05 · for vs while Loops · 5 of 15

When to use for and when to use while?

Use for loop when:

  • You know how many times you want to repeat
  • You want to go through each item of a list, tuple, set or dictionary
  • You are using range()

Use while loop when:

  • You don’t know in advance how many times the loop will run
  • You want to repeat until a certain condition becomes False
  • You are waiting for user input or some external condition

Same task done with both loops:

Python
# Using for
print("Using for loop:")
for i in range(1, 6):
    print(i)

# Using while
print("Using while loop:")
i = 1
while i <= 5:
    print(i)
    i = i + 1
06 · Looping Lists Loops · 6 of 15

Looping through Lists

Lists are the most common data type used with loops.

Method 1 – Direct iteration (most common)

Python
fruits = ["apple", "banana", "mango", "orange"]

for fruit in fruits:
    print(fruit)

Method 2 – Using index

Python
fruits = ["apple", "banana", "mango", "orange"]

for i in range(len(fruits)):
    print("Index:", i, "Value:", fruits[i])

Method 3 – while loop with list

Python
fruits = ["apple", "banana", "mango", "orange"]
i = 0

while i < len(fruits):
    print(fruits[i])
    i = i + 1

Practical Example – Calculating total and average

Python
marks = [78, 85, 92, 67, 88]

total = 0
for m in marks:
    total = total + m

average = total / len(marks)
print("Total:", total)
print("Average:", average)
07 · Looping Tuples Loops · 7 of 15

Looping through Tuples

Tuples work exactly like lists in loops. The only difference is that tuples cannot be changed.

Python
point = (10, 20, 30)

for value in point:
    print(value)

Unpacking inside loop (very useful)

Python
students = [
    ("Rahul", 85),
    ("Priya", 92),
    ("Amit", 78),
    ("Sneha", 95)
]

for name, marks in students:
    print(name, "scored", marks)

    if marks >= 90:
        print("  → Excellent")
Here each item in the list is a tuple. We unpack the tuple directly in the for statement into name and marks.

Using while with tuple

Python
colors = ("red", "green", "blue", "yellow")
i = 0

while i < len(colors):
    print(colors[i])
    i += 1
08 · Looping Sets Loops · 8 of 15

Looping through Sets

You can loop through a set, but remember:

  • Sets are unordered → order of items is not guaranteed
  • Sets do not support indexing (no set[0])
Python
skills = {"python", "sql", "excel", "powerbi", "tableau"}

print("My skills:")
for skill in skills:
    print("-", skill)

Practical Example – Checking required skills

Python
required = {"python", "sql", "excel"}
candidate = {"python", "sql", "powerbi", "excel", "ml"}

print("Checking required skills:")
for skill in required:
    if skill in candidate:
        print(skill, "→ Found")
    else:
        print(skill, "→ Missing")
09 · Looping Dictionaries Loops · 9 of 15

Looping through Dictionaries

Dictionaries are extremely common in data work. There are three main ways to loop through them.

1. Loop through keys only

Python
student = {
    "name": "Kundan",
    "age": 22,
    "course": "Data Analytics",
    "marks": 87
}

for key in student:
    print(key)

# Same thing
for key in student.keys():
    print(key)

2. Loop through values only

Python
for value in student.values():
    print(value)

3. Loop through keys and values together (most useful)

Python
for key, value in student.items():
    print(key, "→", value)

Practical Example – Printing student details

Python
students = [
    {"name": "Rahul", "marks": 85},
    {"name": "Priya", "marks": 92},
    {"name": "Amit", "marks": 78}
]

for s in students:
    print(s["name"], "scored", s["marks"])
    
    if s["marks"] >= 90:
        print("  Grade: A+")
    elif s["marks"] >= 80:
        print("  Grade: A")
    else:
        print("  Grade: B")
10 · enumerate() & zip() Loops · 10 of 15

enumerate() and zip()

enumerate() gives you both index and value while looping.

Python
fruits = ["apple", "banana", "mango"]

for index, fruit in enumerate(fruits):
    print(index, fruit)

# You can also start from 1
for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

zip() lets you loop through two or more lists at the same time.

Python
names = ["Rahul", "Priya", "Amit"]
marks = [85, 92, 78]

for name, score in zip(names, marks):
    print(name, "→", score)
11 · break Statement Loops · 11 of 15

The break Statement

break is used to exit the loop immediately, even if the condition is still True or items are remaining.

Python
numbers = [10, 25, 30, 45, 50, 60]

for num in numbers:
    if num == 45:
        print("Found 45 → stopping the loop")
        break
    print(num)

print("Loop ended")
Output:
10
25
30
Found 45 → stopping the loop
Loop ended

When 45 is found, break is executed and the remaining numbers (50, 60) are not processed.

With while loop

Python
count = 1
while count <= 10:
    print(count)
    if count == 5:
        break
    count += 1
12 · continue Statement Loops · 12 of 15

The continue Statement

continue skips the current iteration and moves to the next one. It does not stop the entire loop.

Python
numbers = [10, 25, 30, 45, 50, 60]

for num in numbers:
    if num == 30:
        continue      # skip this number
    print(num)
Output:
10
25
45
50
60

30 was skipped because of continue.

Practical use – Skip invalid data

Python
marks = [78, -5, 92, 0, 85, -10, 67]

print("Valid marks:")
for m in marks:
    if m <= 0:
        continue
    print(m)
13 · else with Loops Loops · 13 of 15

else Clause with Loops

Python allows an else block with both for and while loops. The else block runs only when the loop finishes normally (not by break).

Python
numbers = [2, 4, 6, 8, 10]

for num in numbers:
    if num % 2 != 0:
        print("Odd number found")
        break
else:
    print("All numbers are even")
Because no odd number was found, the loop completed normally and the else block ran.
14 · Nested Loops Loops · 14 of 15

Nested Loops

A loop inside another loop is called a nested loop.

Python
for i in range(1, 4):
    for j in range(1, 4):
        print(i, "x", j, "=", i*j)
    print("------")

Real Example – Printing student marks subject-wise

Python
students = {
    "Rahul": [85, 90, 78],
    "Priya": [92, 88, 95],
    "Amit": [70, 75, 80]
}

for name, marks in students.items():
    print("Student:", name)
    total = 0
    for m in marks:
        print("  Subject marks:", m)
        total += m
    print("  Total:", total)
    print("------")
15 · Real Examples Loops · 15 of 15

Real-World Examples

Example 1 – Filter customers using for loop

Python
customers = [
    {"name": "Amit", "balance": 45000, "city": "Delhi"},
    {"name": "Priya", "balance": 82000, "city": "Mumbai"},
    {"name": "Rahul", "balance": 15000, "city": "Delhi"},
    {"name": "Sneha", "balance": 95000, "city": "Bangalore"}
]

print("Customers with balance > 50000:")
for cust in customers:
    if cust["balance"] > 50000:
        print(cust["name"], "→", cust["balance"])

Example 2 – Using while loop for menu

Python
while True:
    print("\n1. View Balance")
    print("2. Deposit")
    print("3. Exit")
    
    choice = input("Enter your choice: ")
    
    if choice == "1":
        print("Your balance is 25000")
    elif choice == "2":
        print("Deposit successful")
    elif choice == "3":
        print("Thank you!")
        break
    else:
        print("Invalid choice")

Example 3 – Combining for + condition + dictionary

Python
sales = {
    "Jan": 45000,
    "Feb": 52000,
    "Mar": 48000,
    "Apr": 61000,
    "May": 39000
}

print("Months with sales above 50000:")
for month, amount in sales.items():
    if amount > 50000:
        print(month, "→", amount)
Home Loops in Python

Loops in Python

Complete and detailed explanation of for and while loops with all data types.

Select any topic from the left sidebar to begin.


Start Learning →