1.

Carefully observe the following python code and answer the question that follows:x=5 def func2(): x=3 global x x=x+1 print x print x On execution the above code produces the following output. 6 3 Explain the output with respect to the scope of the variables.

Answer»

Names declared with global keyword have to be referred at the file level. This is because of the global scope. If no global statement is being used the variable with the local scope is accessed. 

Hence, in the above code, the statement succeeding the statement global x informs Python to increment the global variable x 

Hence, the output is 6 i.e. 5 + 1 which is also the value for global x. When x is reassigned with the value 3 the local x hides the global x and hence 3 printed. 

(2 marks for explaining the output) (Only 1 mark for explaining global and local namespace.)



Discussion

No Comment Found