What does 'scope' refer to in Python?
A
The indentation level of code
B
The visibility and lifetime of a variable
C
The number of functions in a file
Analysis & Theory
Scope defines where a variable can be accessed or modified in the code.
Which of the following scopes does Python support?
A
Global, Local, Enclosed, Built-in
B
Public, Private, Protected
Analysis & Theory
Python supports four scopes: Local, Enclosing, Global, and Built-in (LEGB Rule).
What is the output?
def func():
x = 10
print(x)
func()
Analysis & Theory
The variable `x` is defined in the local scope of `func()`, so it prints 10.
What is a global variable?
A
A variable declared inside a loop
B
A variable declared inside a function
C
A variable declared outside any function
D
A variable declared in a class
Analysis & Theory
A global variable is declared outside any function and can be accessed globally.
How do you modify a global variable inside a function?
A
Use the `nonlocal` keyword
B
Just assign a new value
C
Use the `global` keyword
Analysis & Theory
To modify a global variable inside a function, use the `global` keyword.
What will this code print?
x = 5
def change():
x = 10
change()
print(x)
Analysis & Theory
The assignment `x = 10` inside `change()` is local. The global `x` remains 5.
Which keyword allows access to an outer function’s variable in a nested function?
Analysis & Theory
The `nonlocal` keyword allows access and modification of a variable from the enclosing scope.
What is the output?
def outer():
x = 'Python'
def inner():
print(x)
inner()
outer()
Analysis & Theory
The inner function can access the variable `x` from the outer function's enclosing scope.
Where is a built-in scope variable defined?
C
In Python's built-in namespace
Analysis & Theory
Built-in scope refers to names like `len`, `print`, etc., which are available globally by default.
Which of the following correctly demonstrates use of `global` keyword?
B
def func(): global x; x = 5
Analysis & Theory
To modify a global variable inside a function, use `global x` before assignment.