- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use a global variable in a Python function?
There are 2 types of variables in Python namely Local variables and Global variables. Local variables mean the variables that are declared inside a function or inside a method whose impact or scope is only present inside that specific block and it doesn't affect the program outside that block.
Global variables mean the variables that are declared outside any function or method and these variables have an impact or scope through the entire program.
We can also instantiate global variables inside a function by using a global keyword, if we want to declare global variables outside a function then we may not need to use a global keyword.
If a variable with the same name globally and locally then inside the function where the local variable is declared the local value is used and the global value is used elsewhere.
Let us see an example for a global variable in python −
a = 5 def local(): a = 3 print("Value of local variable a is ",a) local() print("Value of global variable a is ",a)
('Value of local variable a is ', 3) ('Value of global variable a is ', 5)
Following is another example for this −
a = 5 def globalV(): print("The value of a is ",a) globalV()
('The value of a is ', 5)
In the following example we are defining two global variables after the function −
def product(): return a * b a = 10 b = 5 print(product())
Now let us let us try to create a global variable with in a function using the “global” keyword −
def func(): global a a = 7 func() b = 5 add = a + b print(add)
Following example shows how the global variable is accessed both inside and outside the function sample.
# This function uses global variable k k = "I like green tea" def sample(): print k #accessing global variable inside function sample() print k #accessing global variable outside function
I like green tea I like green tea
Start learning Python from here: Python Tutorial
Kickstart Your Career
Get certified by completing the courseGet Started