Python Loops

Python Loops Introduction

Loops are one of the most important concepts in Python. They allow you to execute a block of code repeatedly, which makes tasks like iterating through lists, performing calculations, or automating repetitive operations much easier

A loop in Python is used to execute a set of statements multiple times until a certain condition is met. This helps avoid writing the same code over and over again. There are mainly two types of loops in Python:

  • for loop
  • while loop

The range() function is commonly used in loops to generate a sequence of numbers. It’s very useful when you want to repeat an action a specific number of times.

Syntax:

range(start, stop, step)

  • start – the starting number (default is 0)
  • stop – the number at which the range ends (not included)
  • step – the difference between each number (default is 1)
Example 1:
Here, the loop runs 5 times, printing numbers from 0 to 4.

for i in range(5):
print(i)
Output :
0
1
2
3
4
Example 2:

for i in range(2, 10, 2):
    print(i)
Output :
2
4
6
8

A for loop is used when you know how many times you want to execute a block of code. It’s great for iterating through sequences like lists, tuples, or strings.

# Example 1: Iterating through a list|

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

apple
banana
cherry
# Example 2: Iterating through a string

for letter in "Python":
    print(letter)
Output:
P
y
t
h
o
n

A nested loop means having one loop inside another. This is often used for working with multidimensional data, like matrices or tables.

# Example:
for i in range(1, 4):
    for j in range(1, 4):
        print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3

Here, the inner loop runs completely every time the outer loop runs once

A while loop continues to run as long as a given condition is True. You use it when you don’t know how many times you need to repeat a block of code.

Example:

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

Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4

If the condition never becomes False, the loop runs forever (an infinite loop). To avoid that, always make sure the condition changes within the loop.


The break statement is used to stop a loop immediately, even if the loop’s condition is still True.

# Example:

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

0
1
2
3
4

The loop stops when i equals 5, skipping the rest of the iterations.

The continue statement is used to skip the rest of the code inside a loop for the current iteration and move to the next one

# Example:

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)
Output:

1
3
5
7
9

Here, every time i is even, the loop skips the print() statement and continues to the next iteration.

You can use both break and continue in the same loop to control its flow precisely.

# Example:

for i in range(10):
    if i == 3:
        continue
    if i == 8:
        break
    print(i)
Output:

0
1
2
4
5
6
7

When i is 3, the continue statement skips that iteration. When i reaches 8, the break statement stops the loop entirely

Here’s a simple example that uses both a while loop and break:

password = "python123"
attempts = 0

while attempts < 3:
    guess = input("Enter password: ")
    if guess == password:
        print("Access granted!")
        break
    else:
        print("Wrong password, try again.")
        attempts += 1
else:
    print("Too many attempts. Access denied.")

# This loop lets the user try three times before locking them out

ConceptDescriptionExample
for loopRuns a block of code a set number of timesfor i in range(5): print(i)
while loopRuns as long as a condition is truewhile x < 10:
range()Generates a sequence of numbersrange(1, 10, 2)
breakStops the loopif i == 5: break
continueSkips current iterationif i % 2 == 0: continue
Nested loopA loop inside anotherfor i in range(3): for j in range(3): …