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
for number in range(1, 6):
print(number)1 2 3 4 5
Example
for (let number = 1; number <= 5; number++) {
console.log(number);
}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:
let number = 1- where to startnumber <= 5- keep going while this is truenumber++- 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
students = ["Ali", "Ayesha", "Bilal"]
for name in students:
print("Welcome,", name)Welcome, Ali Welcome, Ayesha Welcome, Bilal
Example
let students = ["Ali", "Ayesha", "Bilal"];
for (let name of students) {
console.log("Welcome,", name);
}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
sales = [1200, 850, 2300, 400]
total = 0
for amount in sales:
total = total + amount
print("Total sales: Rs", total)Total sales: Rs 4750
Example
let sales = [1200, 850, 2300, 400];
let total = 0;
for (let amount of sales) {
total = total + amount;
}
console.log("Total sales: Rs", total);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
savings = 0
months = 0
while savings < 10000:
savings = savings + 3000
months = months + 1
print("Months needed:", months)Months needed: 4
Example
let savings = 0;
let months = 0;
while (savings < 10000) {
savings = savings + 3000;
months = months + 1;
}
console.log("Months needed:", months);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
items = ["pen", "eraser", "ruler", "sharpener"]
for item in items:
if item == "ruler":
print("Found the ruler!")
break
print("Checked", item)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")
