Consider the following code:
x = 5
def test(a):
_________________ # Missing Statement
x = x + a
print(a, x)
test(3)
If the output produced is 3 8, which of the following statements should be given in the blank for the missing statement?
Options:
-
global a
-
global x
-
global x=5
-
global a=5
Answer:
Answer by student
b) global x
Detailed answer by teachoo
-lock-
The global keyword is used to create a global variable and make changes to the variable in a local context, i.e. inside a function. The global keyword is used inside a function only when we want to do assignments or when we want to change a variable.
Let’s go through each of the options and see why they are correct or incorrect.
a) global a: This option is incorrect because it declares a as a global variable, not x. This means that the value of a will be accessible and modifiable outside the function, but not x. The statement x = x + a will cause an error because x is a local variable that is not defined yet.
b) global x: This option is correct because it declares x as a global variable. This means that the value of x will be accessible and modifiable both inside and outside the function. The statement x = x + a will work because x refers to the global variable that has an initial value of 5.
c) global x=5: This option is incorrect because it is not a valid syntax for using the global keyword. The global keyword should be followed by a variable name, not an assignment statement. This will cause a syntax error.
d) global a=5: This option is incorrect because it is also not a valid syntax for using the global keyword. The global keyword should be followed by a variable name, not an assignment statement. This will cause a syntax error.
So, the correct answer is b) global x
-endlock-