0 votes
in Computer by (45.7k points)
closed by

Explain the use of global key word used in a function with the help of a suitable example.

1 Answer

+1 vote
by (48.9k points)
selected by
Best answer

Use of global key word: 

In Python, global keyword allows the programmer to modify the variable outside the current scope. It is used to create a global variable and make changes to the variable in local context. A variable declared inside a function is by default local and a variable declared outside the function is global by default. The keyword global is written inside the function to use its global value. Outside the function, global keyword has no effect. 

Example :

c = 10 # global variable

def add(): global c 

c = c + 2    # global value of c is incremented by 2 

print("Inside add():", c) 


c=15 print("In main:", c) 


Inside add() : 12 

In main: 15

Related questions

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.