In: Computer Science
In the python code below, describe the scope of the variables x, y, z and u.
def my_func(x):
y = x - 2
return y
z = 6
if z > 4:
u =
my_func(6)
print(u)
Hi, if you like my answer, then please give an upvote. In case you have any doubts regarding my answer, tell me in the comments. I would be very happy to help you again.
The scope of a variable can either be local or global. When we create and use a variable inside a function then the scope of that variable is limited to that function only and it cannot be used outside that function. This is called Local Variables On the other hand, if we declare and use variables outside the functions then the values of those variables can be used inside any function also. This is called the Global Variables.
In the given code, variables 'x' and 'y' are created inside the function my_func, so they are local variables, as their scope is inside that function only. But the variables 'z' and 'u' are created outside any function, in the body of Python code, so they are Global variables, as their scope is not limited.