Intro to Programming Tutorial menu

Loops

A loop repeats a block of code many times, so you do not have to write the same line again and again.

Why We Need Loops

Suppose you want to print the numbers 1 to 5. Without a loop you write five lines. For 1 to 1000 you would need a thousand lines. A loop does it in two or three lines, whatever the count.

There are two main kinds of loops:

  • A for loop: repeat a fixed number of times, or once for each item in a list
  • A while loop: keep repeating as long as a condition is true

The for Loop

Print the numbers 1 to 5:

Example

python
for number in range(1, 6):
    print(number)
Output
1
2
3
4
5

Example

javascript
for (let number = 1; number <= 5; number++) {
  console.log(number);
}
Output
1
2
3
4
5

In Python, range(1, 6) gives the numbers from 1 up to, but not including, 6.

In JavaScript, the round brackets have three parts separated by semicolons:

  1. let number = 1 - where to start
  2. number <= 5 - keep going while this is true
  3. number++ - add 1 after each round

Looping Over a List

A list (called an array in JavaScript) holds several values in one variable, inside square brackets. Loops and lists work very well together.

Example

python
students = ["Ali", "Ayesha", "Bilal"]
for name in students:
    print("Welcome,", name)
Output
Welcome, Ali
Welcome, Ayesha
Welcome, Bilal

Example

javascript
let students = ["Ali", "Ayesha", "Bilal"];
for (let name of students) {
  console.log("Welcome,", name);
}
Output
Welcome, Ali
Welcome, Ayesha
Welcome, Bilal

The loop runs once for each item. Each time, the variable name holds the next item.

Adding Up with a Loop

A common job is to add up numbers. Here a shopkeeper totals one day's sales in rupees:

Example

python
sales = [1200, 850, 2300, 400]
total = 0
for amount in sales:
    total = total + amount
print("Total sales: Rs", total)
Output
Total sales: Rs 4750

Example

javascript
let sales = [1200, 850, 2300, 400];
let total = 0;
for (let amount of sales) {
  total = total + amount;
}
console.log("Total sales: Rs", total);
Output
Total sales: Rs 4750

We start total at 0, and each round adds one amount to it. The final print is outside the loop, so it runs only once at the end.

The while Loop

A while loop repeats as long as its condition is true. It is useful when you do not know in advance how many rounds you need.

Example

python
savings = 0
months = 0
while savings < 10000:
    savings = savings + 3000
    months = months + 1
print("Months needed:", months)
Output
Months needed: 4

Example

javascript
let savings = 0;
let months = 0;
while (savings < 10000) {
  savings = savings + 3000;
  months = months + 1;
}
console.log("Months needed:", months);
Output
Months needed: 4

After 3 months there are Rs 9000 saved, which is still less than 10000, so the loop runs a fourth time.

Be careful: if the condition never becomes false, the loop runs forever. This is called an infinite loop. Always make sure something inside the loop moves it closer to the end. If a program gets stuck, press Ctrl + C to stop it.

Stopping Early with break

break exits a loop straight away. Here we search a list and stop when we find what we want:

Example

python
items = ["pen", "eraser", "ruler", "sharpener"]
for item in items:
    if item == "ruler":
        print("Found the ruler!")
        break
    print("Checked", item)
Output
Checked pen
Checked eraser
Found the ruler!

The same idea works in JavaScript with the same keyword, break.

Exercise

Exercise

How many times does print run in Python: for i in range(3): print("Hi")

Learn Intro to Programming 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