Python Loops
Loops repeat a block of code, so you do not have to write the same lines again and again.
The for Loop
A for loop goes through each item of a sequence (a list, a string, a range and so on):
Example
foods = ["nihari", "haleem", "karahi"]
for food in foods:
print("I like", food)I like nihari I like haleem I like karahi
It also works on a string, one character at a time:
Example
for letter in "Ali":
print(letter)A l i
The range() Function
range() gives a sequence of numbers. It is perfect when you want to repeat something a set number of times.
| Code | Numbers |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 6) | 1, 2, 3, 4, 5 |
range(0, 20, 5) | 0, 5, 10, 15 |
range(5, 0, -1) | 5, 4, 3, 2, 1 |
Example
for i in range(1, 6):
print(f"5 x {i} = {5 * i}")5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25
The end number in range() is never included. range(1, 6) stops at 5.
The while Loop
A while loop runs as long as its condition is True:
Example
savings = 0
month = 0
while savings < 10000:
savings += 3000
month += 1
print(f"Goal reached in {month} months with Rs {savings}")Goal reached in 4 months with Rs 12000
Make sure something inside the loop changes, so the condition becomes False one day. Otherwise the loop runs forever.
break and continue
breakstops the loop completelycontinueskips the rest of this round and goes to the next one
Example
for n in range(1, 10):
if n == 6:
break
if n % 2 == 0:
continue
print(n)1 3 5
Even numbers are skipped by continue, and the loop ends at 6 because of break.
Looping With an Index
enumerate() gives you both the position and the item:
Example
toppers = ["Ayesha", "Bilal", "Sana"]
for position, name in enumerate(toppers, start=1):
print(position, name)1 Ayesha 2 Bilal 3 Sana
else With a Loop
A loop can have an else block. It runs when the loop finishes normally, without break:
Example
for i in range(3):
print(i)
else:
print("Done")0 1 2 Done
Nested Loops
A loop inside another loop runs fully for each round of the outer loop:
Example
for row in range(1, 4):
print("*" * row)* ** ***
Example
for size in ["S", "M"]:
for color in ["red", "blue"]:
print(size, color)S red S blue M red M blue
Exercise
Exercise
How many times does this loop print? for i in range(2, 8, 2): print(i)
