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:

  1. global a

  2. global x

  3. global x=5

  4. 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-

Remove Ads
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.