What is a loop in programming?
In short
A loop repeats a block of code, either a set number of times or for as long as a condition stays true.
Computers are good at doing the same thing many times without getting bored. A loop is how you ask them to. Instead of writing the same line ten times, you write it once inside a loop that runs ten times.
A for loop is usually used to go through a range of numbers or every item in a list. A while loop keeps going until something changes, like the user typing "quit".
Python
Count from 1 to 3, then add up a list
for n in range(1, 4):
print(n)
total = 0
for price in [3, 5, 2]:
total = total + price
print(total)Output
1
2
3
10JavaScript
The same idea in JavaScript
for (let n = 1; n <= 3; n++) {
console.log(n);
}
let total = 0;
for (const price of [3, 5, 2]) {
total = total + price;
}
console.log(total);Output
1
2
3
10Learn it properly
These free lessons teach it step by step, with questions and a program you write yourself.
- for Loops and range()Learn Python →
- while Loops and breakLearn Python →
- while and for LoopsLearn JavaScript →
- for LoopsLearn C →
Try your first lesson free
Codiqo teaches coding in five-minute lessons with real code. Free on the web, iPhone and Android.