Loops
Imagine you need to print numbers from 1 to 100. Writing 100 print statements would be tedious. Loops let you repeat a block of code multiple times. Python provides two main loop types: `for` and `while`.
for loop
The `for` loop iterates over a sequence (list, tuple, string, range).
# Iterate over a range of numbers
for i in range(5):
print(i) # 0,1,2,3,4
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate over characters of a string
for ch in "Python":
print(ch)
while loop
The `while` loop continues as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1
range() function
`range(start, stop, step)` generates a sequence of numbers.
# range(stop)
for i in range(3): # 0,1,2
# range(start, stop)
for i in range(2, 5): # 2,3,4
# range(start, stop, step)
for i in range(0, 10, 2): # 0,2,4,6,8
Two Minute Drill
- `for` loop iterates over sequences; `while` loops while condition is true.
- `range()` generates numeric sequences for loops.
- Always ensure `while` loops eventually terminate (update condition).
- Use loops to avoid repetitive code.
Need more clarification?
Drop us an email at career@quipoinfotech.com
