What are Loops?
A loop is used to execute a block of code repeatedly.
Python mainly provides two types of loops:
for Loop
Used to iterate over a sequence or range of values.
while Loop
Repeats code while a condition remains True.
1. for Loop
The for loop is used to
repeat a block of code for each item
in a sequence.
for i in range(5):
print(i)
0 1 2 3 4
2. range() Function
The range() function generates
a sequence of numbers.
for i in range(1, 6):
print(i)
1 2 3 4 5
The ending value in range()
is not included.
3. while Loop
A while loop executes a block
of code as long as its condition is True.
i = 1
while i <= 5:
print(i)
i += 1
1 2 3 4 5
4. break Statement
The break statement stops
the loop immediately.
for i in range(1, 6):
if i == 4:
break
print(i)
1 2 3
5. continue Statement
The continue statement skips
the current iteration and moves to the
next iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)
1 2 4 5
6. Practical Example
We can use loops to print the multiplication table of a number.
number = 5
for i in range(1, 11):
print(number, "x", i, "=", number * i)
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 ... 5 x 10 = 50
for is commonly used when
iterating over a sequence or a known range.
while is useful when repetition
depends on a condition.
Quick Quiz
Which keyword stops a loop immediately?
Finished this lesson?