Block scope refers to the visibility and lifetime of variables that are defined within a specific block of code, typically enclosed by curly braces {} in many programming languages like JavaScript, C++, and Java. In block scope, variables declared inside a block are only accessible within that block and are not visible outside of it.
For example, in JavaScript:
{
let x = 10;
console.log(x); // Output: 10
}
console.log(x); // Error: x is not defined
In the above code, the variable x is declared inside a block and can only be accessed within that block. Trying to access x outside the block results in an error because x is not defined in the outer scope.
In contrast, Python does not have block scope for variables declared inside loops or conditionals, but it does have block scope for variables declared inside functions.
For example, in Python:
if True:
x = 10
print(x) # Output: 10
def my_function():
y = 20
print(y) # Output: 20
my_function()
print(y) # Error: NameError: name 'y' is not defined
In this Python example, the variable x is accessible outside the if block, but the variable y is not accessible outside the function my_function.
Whenever we access any name in Python — a variable name, function name, class name, etc., the Python interpreter searches it in the following order:
This is often called the LEGB rule.
After running a for-loop, the loop variable is still accessible. After running a list comprehension, the loop variable is NOT accessible.