Python Tutorial menu

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

python
foods = ["nihari", "haleem", "karahi"]
for food in foods:
    print("I like", food)
Output
I like nihari
I like haleem
I like karahi

It also works on a string, one character at a time:

Example

python
for letter in "Ali":
    print(letter)
Output
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.

CodeNumbers
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

python
for i in range(1, 6):
    print(f"5 x {i} = {5 * i}")
Output
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

python
savings = 0
month = 0
while savings < 10000:
    savings += 3000
    month += 1
print(f"Goal reached in {month} months with Rs {savings}")
Output
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

  • break stops the loop completely
  • continue skips the rest of this round and goes to the next one

Example

python
for n in range(1, 10):
    if n == 6:
        break
    if n % 2 == 0:
        continue
    print(n)
Output
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

python
toppers = ["Ayesha", "Bilal", "Sana"]
for position, name in enumerate(toppers, start=1):
    print(position, name)
Output
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

python
for i in range(3):
    print(i)
else:
    print("Done")
Output
0
1
2
Done

Nested Loops

A loop inside another loop runs fully for each round of the outer loop:

Example

python
for row in range(1, 4):
    print("*" * row)
Output
*
**
***

Example

python
for size in ["S", "M"]:
    for color in ["red", "blue"]:
        print(size, color)
Output
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)

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp