Sometimes you loop over numbers rather than an existing collection, do this ten times, print every year from 1954 to 1968.
Python pairs for with range. JavaScript uses its classic three-part counting loop: start, condition, step.
Counting
PYTHON
for i in range(5):
print(i)
≈
JAVASCRIPT
for (let i = 0; i < 5; i++) {
console.log(i);
}
Compare → JavaScript's three parts read: start i at 0; keep going while i < 5; add 1 each pass (i++ means i += 1). Python hides that machinery inside range. Same five passes, 0 through 4. This is a DIFFERENT SYNTAX for a shared concept.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Five passes, starting at 0. Now change it to print 1 through 5 instead, in Python adjust the range, in JavaScript adjust the start and condition.
loading editor…
Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Python's third range argument is the step. JavaScript steps with n += 2. Now print every odd number from 1 to 9.
loading editor…
Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.
Mark this lesson complete
Signed in, your progress follows you to every device.