Course
BASICModule 2: Loops & Functions· 1/3

Loops

Repetition without copy-paste

You need to print a greeting for five users. You could copy the line five times — but what if there are ten thousand users? A loop solves "repeat N times" with one construct. Loops are where the computer's speed starts working for you.

PLAYGROUND

Breakdown of for in JavaScript: three parts separated by semicolons — start (let i = 1), continue condition (i <= 5), step after each pass (i++ — increase by 1). Python is more compact: range(1, 6) yields numbers 1 to 5 (the right boundary is not included — get used to it, it's a common question).

The variable i is a counter: inside the loop it's available and changes on every pass. Half of all useful loops are built on it.

Looping over a collection

Most often a loop iterates not over numbers but over items in a list (lists in detail — in module 3; here's a first look):

PLAYGROUND

It reads almost like English: "for each coin in the list — do." 90% of real loops are exactly this: iterate over orders, files, table rows, wallets.

A conditional loop: while

for repeats a set number of times; while — as long as a condition is true:

PLAYGROUND

The main danger of loops is tied to while — the infinite loop: if the condition never becomes false, the program hangs. Remove the line that grows the balance and run it — the playground will abort by timeout, but a real script would hang forever. Rule: inside a while body, something must move the condition toward false.

Accumulator: the main loop pattern

The most common task is to walk over data and accumulate a result: a sum, a count, a maximum. The pattern: create a tally variable before the loop, top it up inside:

PLAYGROUND

Notice: a condition lives inside the loop — constructs nest inside each other like Russian dolls. Programs of any complexity are built from these blocks.

Exercise

Count how many numbers in the list are even. Hint: evenness is checked by the remainder — x % 2 === 0 (JS) / x % 2 == 0 (Python).

PLAYGROUND

Key takeaways

  • for — repeat N times or iterate over a collection; while — repeat while a condition is true.
  • range(1, 6) in Python — numbers 1..5: the right boundary is not included.
  • Infinite loop: a while body must move the condition toward false.
  • Accumulator pattern: a tally before the loop, top-up inside — sum, count, maximum.
CHECK YOURSELF
1. How many numbers does range(0, 10) produce in Python?
2. A program with while hangs forever. The most likely cause?
3. You need the sum of all orders from a list. Which pattern?
Conditions & LogicFunctions