Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
4.9k views
in Computer by (72.4k points)

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. 

Explain the output with respect to the scope of the variables.

1 Answer

0 votes
by (89.4k points)
selected by
 
Best 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.)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...