Python Loops Basics

October 7, 2025

Loops are one of the most powerful concepts in any programming language.
They allow you to repeat a block of code multiple times β€” saving effort, avoiding repetition, and making your programs more efficient.

In this guide, you’ll learn everything about Python loops, including:

  • for loop
  • while loop
  • break, continue, and pass statements
  • Loop else blocks
  • Common examples and use cases

Let’s dive in! πŸš€


🧠 What is a Loop?

A loop allows you to execute a block of code repeatedly until a certain condition is met.

There are mainly two types of loops in Python:

  1. for loop – Used for iterating over a sequence (like list, tuple, dictionary, string, or range).
  2. while loop – Used for repeating a block of code as long as a condition is True.

πŸ”Ή 1. for Loop

The for loop is used when you want to iterate over a sequence (like a list, tuple, or string) and perform actions for each element.

🧩 Syntax:

for variable in sequence:
    # Code block


βœ… Example 1: Looping through a list

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry


βœ… Example 2: Looping through a string

for char in "Python":
    print(char)

Output:

P
y
t
h
o
n


βœ… Example 3: Using range() in loops

The range() function generates a sequence of numbers.

for i in range(5):
    print(i)

Output:

0
1
2
3
4

πŸ‘‰ By default, range(start, stop, step) starts at 0 and stops before the given number.

Example with step:

for i in range(2, 10, 2):
    print(i)

Output:

2
4
6
8


βœ… Example 4: Looping through a list using range()

Sometimes, you may want to use indexes while looping through a list β€” for example, when you need both the index and the value.

fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
    print(f"Index {i}: {fruits[i]}")

Output:

Index 0: apple
Index 1: banana
Index 2: cherry

πŸ’‘ Tip:
You can also use the built-in enumerate() function for cleaner index-based looping:

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


βœ… Example 5: Looping through a dictionary

When looping through dictionaries, you can iterate over:

  • Keys
  • Values
  • Key-value pairs
person = {"name": "Alice", "age": 25, "city": "Mumbai"}

# Loop through keys
for key in person:
    print(key)

# Loop through values
for value in person.values():
    print(value)

# Loop through key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

Output:

name
age
city
Alice
25
Mumbai
name: Alice
age: 25
city: Mumbai


πŸ”Ή 2. while Loop

A while loop executes a block of code as long as the condition is True.

🧩 Syntax:

while condition:
    # Code block

βœ… Example: Counting numbers

count = 1
while count <= 5:
    print(count)
    count += 1

Output:

1
2
3
4
5

⚠️ If the condition never becomes False, the loop runs forever (infinite loop).


πŸ”Έ 3. Loop Control Statements

Python provides three special statements to control the flow of loops:

➀ break

Stops the loop entirely when a certain condition is met.

for i in range(10):
    if i == 5:
        break
    print(i)

Output:

0
1
2
3
4


➀ continue

Skips the current iteration and moves to the next one.

for i in range(6):
    if i == 3:
        continue
    print(i)

Output:

0
1
2
4
5


➀ pass

Used as a placeholder when you don’t want to execute any code yet.

for i in range(5):
    pass  # Placeholder for future code


πŸ”Έ 4. Loop else Block

An else block can be added to loops in Python.
The else part runs after the loop finishes normally (not when stopped by break).

βœ… Example:

for i in range(5):
    print(i)
else:
    print("Loop completed successfully!")

Output:

0
1
2
3
4
Loop completed successfully!


πŸ”Ή 5. Nested Loops

You can place one loop inside another loop β€” useful for working with multi-dimensional data like matrices or nested lists.

for i in range(1, 4):
    for j in range(1, 4):
        print(f"({i}, {j})", end=" ")
    print()

Output:

(1, 1) (1, 2) (1, 3) 
(2, 1) (2, 2) (2, 3) 
(3, 1) (3, 2) (3, 3)


🧰 6. Common Loop Use Cases

Use CaseExample
Print numbers 1–10for i in range(1, 11): print(i)
Sum of numberssum = 0; for i in range(1,6): sum += i
Loop through dictionaryfor k,v in dict.items(): print(k,v)
Search element in listfor item in list: if item==target: break
Filter even numbers[x for x in range(10) if x%2==0]

πŸ” Bonus: List Comprehensions (Short Loops in One Line)

Python allows loops in a single line to create lists concisely.

squares = [x**2 for x in range(5)]
print(squares)

Output:

[0, 1, 4, 9, 16]


🧩 Summary Table

TypeSyntaxUse Case
for loopfor i in sequence:Iterate over sequences (lists, strings, etc.)
while loopwhile condition:Repeat until condition becomes False
breakβ€”Stop loop early
continueβ€”Skip current iteration
passβ€”Placeholder (does nothing)
elsefor/while ... else:Runs when loop finishes normally

πŸ’‘ Final Thoughts

Loops are the core building blocks of Python programming.
They make your code more efficient and dynamic by avoiding repetition.

Remember:

  • Use for loops for iterating over collections.
  • Use while loops for condition-based repetition.
  • Use break, continue, and pass to control loop flow.

Β© Copyright 2025 β€” Fessorpro

Terms of Service / Privacy Policy