Topic 10: What are Loops in Python?
What are Loops in Python? Quiz for Loopsπ
Instead of writing the same code again and again, loops let the computer do the repetition automatically.A loop is a programming structure that lets you repeat a block of code multiple times as long as a condition is true or for a specific number of iterations.
A loop is a control structure that executes a group of statements repeatedly as long as a given condition is true. When the condition becomes false, the loop stops executing.
Example:
print("Hello")
print("Hello")
print("Hello")
Instead of writing this three times, you can use a loop:
for i in range(3):
print("Hello")Python supports mainly two types of loops:
-
while loop
-
for loop
1. while Loop
The while loop executes a block of code as long as a given condition is True. When the condition becomes false, the loop stops
Syntax:
while condition:
# code to repeat
Example:
i = 1
while i <= 5:
print("Count:", i)
i = i + 1
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
-
The loop starts with
i = 1 -
Runs while
i <= 5 -
Increments
ieach time -
Stops when
ibecomes 6
2. for Loop
The for loop is used to iterate over a sequence (like a list, tuple, string, or range).
Syntax:
for variable in sequence:
# code to execute
Example:
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
Output:
apple
banana
cherry
QUIZ for Loopsπ
For Loop Using range()
The range() function is most commonly used with a for loop when you want to run a loop a specific number of times.
Syntax:
range(start, stop, step)
| Parameter | Description | Example |
|---|---|---|
| start | Starting value (default = 0) | range(2, 5) → starts at 2 |
| stop | Stops before this number | range(2, 5) → ends at 4 |
| step | Interval between values (default = 1) | range(1, 10, 2) → 1,3,5,7,9 |
Example 1:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Example 2:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Example 3: (Using step)
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
Supper π
ReplyDelete