Loops

Reading Time: 3 minutes

What are Loops ?

A loop is used to repeat a block of code multiple times until a condition is met. Without loops, you would have to write repetitive code manually.

Example without loop:

print("Hello")
print("Hello")
print("Hello")
print("Hello")

Using loop:

for i in range(4):
    print("Hello")

Types of Loops in Python

Python mainly supports two types of loops:

  1. for loop
  2. while loop

For Loop in Python

The for loop is used when you know how many times you want to repeat a task.

Example 1: Simple Loop

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

Output:

0
1
2
3
4

range()

The range() function generates a sequence of numbers.

range(start, stop, step)      
range(start, stop)  # step is of 1 by default
range(stop)      # sequence start with 0 and step is 1 by default

Example:

for i in range(1, 6):
    print(i)
1
2
3
4
5

Loop Through List

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

for fruit in fruits:
    print(fruit)

Loop Through String

for char in "Python":
    print(char)

Nested For Loop

A loop inside another loop.

for i in range(3):
    for j in range(2):
        print(i, j)

Example

Print multiplication table:

num = 5

for i in range(1, 11):
    print(num, "x", i, "=", num * i)

While Loop in Python

The while loop is used when you don’t know how many times the loop should run. It continues until a condition becomes False.

Example 1: Simple While Loop

i = 1                    # loop control variable
while i <= 5:       # loop condition # loop block will be be executed until given condition become false.
    print(i)
    i += 1              # variable increment

Output:

1
2
3
4
5

Infinite Loop

If the condition never becomes False, the loop runs forever.

i = 1
while i > 0:
    print(i)

This creates an infinite loop. Always ensure condition changes.

While Loop with User Input

password = ""
while password != "1234":
    password = input("Enter password: ")
print("Access granted")

Break Statement

The break statement is used to exit a loop immediately, even if the condition is still True. or we can say Stop a loop when a certain condition is met.

Example:

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

Output:

0
1
2
3
4

Continue Statement

The continue statement skips the current iteration and moves to the next one.

Example:

for i in range(5):
    if i == 2:
        continue
    print(i)

Output:

0
1
3
4

Combining Loops with Conditions

Example 1: Print all even numbers between 1 to 10

for i in range(1, 11):
    if i % 2 == 0:
        print(i, "is even")

Practical Examples

Example 1: Sum of Numbers

total = 0
for i in range(1, 6):
    total += i
print("Sum =", total)

Example 2: Count Down Timer

i = 5
while i > 0:
    print(i)
    i -= 1

Example 3: Find First Even Number

for i in [5,7,8,2,5,6]:
    if i % 2 == 0:
        print("First even:", i)
        break