InPython,global variables are declared outside any function and can be accessed anywhere in the program, including inside functions. On the other hand, local variablesare created within a function and are only accessible during that function’s execution. This means local variables exist only inside the function where they are defined and cannot be used outside it. Let’s understand each in detail.
Python Local Variables
Local variables are created within a function and exist only during its execution. They're not accessible from outside the function.
Example 1:In this example, we are creating and accessing a local variable inside a function.
Pythondefgreet():msg="Hello from inside the function!"print(msg)greet()
OutputHello from inside the function!
Explanation:We define greet()with a local variablemsg and print it. Since msg exists only during the function's execution, it's accessed within the function. Callinggreet()displays the message.
Example 2: In this example, we are creating a local variable inside a function and then trying to access it outside the function, which causes an error.
Pythondefgreet():msg="Hello!"print("Inside function:",msg)greet()print("Outside function:",msg)
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 6, in <module>
print("Outside function:", msg)
^^^
NameError: name 'msg' is not defined
Explanation: msgis a local variable inside greet() and can only be accessed there. Printing it outside causes an error because it doesn't exist globally.
Python Global Variables
Global variablesare defined outside all functions. They can be accessed and used in any part of the program, including inside functions.
Example 1:In this example, we are creating a global variable and then accessing it both inside and outside a function.
Pythonmsg="Python is awesome!"defdisplay():print("Inside function:",msg)display()print("Outside function:",msg)
OutputInside function: Python is awesome!Outside function: Python is awesome!
Explanation: msg is a global variable accessible both inside and outside thedisplay()function. Callingdisplay()prints the globalmsg and printingmsgoutside the function works as expected.
Example 2:In this example, we're creating a global variable and then using it both inside and outside a function.
Pythondeffun():print("Inside Function",s)# Global scopes="I love Geeksforgeeks"fun()print("Outside Function",s)
OutputInside Function I love GeeksforgeeksOutside Function I love Geeksforgeeks
Explanation: s is a global variable accessed and printed insidefun(). Both callingfun() and printing s outside show the same global value.
Note: As there are no locals, the value from the globals will be used but make sure both the local and the global variables should have same name.
Why do we use Local and Global variables in Python?
If a variable is defined both globally and locally with the same name, the local variable shadows the global variable inside the function. Changes to the local variable do not affect the global variable unless you explicitly declare the variable as global. Example:
Pythondeffun():s="Me too."print(s)s="I love Geeksforgeeks"fun()print(s)
OutputMe too.I love Geeksforgeeks
Explanation:Inside fun(),sis a local variable set to "Me too." and prints that value. Outside, the globals remains "I love Geeksforgeeks", so printingsafterward shows the global value.
What if We Try to Modify a Global Variable Inside a Function?
Attempting to change a global variable inside a function without declaring it as global will cause an error.Example:
Pythondeffun():s+='GFG'print("Inside Function",s)s="I love Geeksforgeeks"fun()
Output
UnboundLocalError: local variable 's' referenced before assignment
Explanation: fun()tries to modifys without declaring it global, so Python treatssas local but it’s used before assignment, causing an error. Declaringsas global insidefun()fixes this.
Modifying Global Variables Inside a Function
To modify a global variable inside a function, you must explicitly tell Python that you want to use the global version by using theglobal keyword. Example:
Pythondeffun():globalss+=' GFG'# Modify the global variableprint(s)s="Look for Geeksforgeeks Python Section"print(s)s="Python is great!"fun()print(s)
OutputPython is great! GFGLook for Geeksforgeeks Python SectionLook for Geeksforgeeks Python Section
Explanation:Insidefun(), the global keyword lets Python modify the global variables directly. The function first appends ' GFG' to "Python is great!", then reassigns s to "Look for Geeksforgeeks Python Section".
Example 2:This example demonstrates how Python handles global and local variables with the same name, and how theglobal keywordaffects their behavior.
Pythona=1# Global variabledeff():print('f():',a)# Uses global adefg():a=2# Local variable shadows globalprint('g():',a)defh():globalaa=3# Modifies global aprint('h():',a)print('global:',a)f()print('global:',a)g()print('global:',a)h()print('global:',a)
Outputglobal: 1f(): 1global: 1g(): 2global: 1h(): 3global: 3
Explanation:
- f()prints the globala without changing it.
- g()creates a local a that shadows the global one, leaving the globala unchanged.
- h()uses global to modify the globala.
- Onlyh() changes the global variable, f() andg() do not.
Difference b/w Local Variable Vs. Global Variables
Understanding local and global variables in Python is key, as they differ in scope and lifetime. Locals exist inside functions and global are accessible everywhere. This knowledge helps prevent bugs and write cleaner code. See the comparison table below for clarity.
Comparison basis | Global Variable | Local Variable |
---|
Definition | Declared outside the functions | Declared within the functions |
---|
Lifetime | They are created the execution of the program begins and are lost when the program is ended | They are created when the function starts its execution and are lost when the function ends |
---|
Data Sharing | Offers Data Sharing | It doesn't offers Data Sharing |
---|
Scope | Can be access throughout the code | Can access only inside the function |
---|
Parameters needed | Parameter passing is not necessary | Parameter passing is necessary |
---|
Storage | A fixed location selected by the compiler | They are kept on the stack |
---|
Value | Once the value changes it is reflected throughout the code | once changed the variable don't affect other functions of the program |
---|