Block Scope and Lifetime

JavaScript adds one more level: let and const are block scoped, meaning they exist only inside the nearest curly braces, including a loop body or an if statement. Python has no block scope, a variable made inside an if or for survives afterwards.

Block scope

PYTHON

for i in range(3):
    last = i

print(last)   # 2, Python keeps it

JAVASCRIPT

for (let i = 0; i < 3; i++) {
  let last = i;
}

console.log(last); // ReferenceError
Compare → A genuine LANGUAGE-SPECIFIC difference, not just syntax. Python scopes to the function, JavaScript scopes `let` to the block. Declare the variable before the loop in JavaScript if you need it afterwards.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Use a loop to find the last even number in [3, 8, 5, 12, 7], declaring the variable that holds it before the loop starts.
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.

Lifetime is the other half of the story. A local variable lives only as long as the call that created it. Call a function three times and you get three separate, independent lifetimes.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Make the counter count: move n outside the function (Python also needs global n inside it) so the three prints show 1, 2 and 3.
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.

◈ Graded Challenge

Write a function that takes a list of numbers and returns how many of them are positive. Use a local accumulator so repeated calls never interfere with each other.

Name it exactly: def count_positive(numbers):

3 visible + 2 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back