[Type B] Working with Functions – Chapter 3 Sumita Arora
Table of Contents
15. In the following code, which variables are in the same scope?
Python
def func1():
a = 1
b = 2
def func2():
c = 3
d = 4
e = 5
Solution: Variables a, b, c, and d are in the same scope, while variable e is in a different scope.
- Variables in the Same Scope: a, b, c, d
- Variables in Different Scope: e
Explanation: In Python, variables defined within a function belong to the scope of that function, meaning they are accessible only within the function in which they are defined.
In this code, variables a
, b
, c
, and d
are defined within functions func1
and func2
, so they are in the same scope. However, variable e
is defined outside of any function, so it is in a different scope and can be accessed globally within the program.