Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Type Conversion in Python
Next article icon

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.

Python
defgreet():msg="Hello from inside the function!"print(msg)greet()

Output
Hello 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.

Python
defgreet():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.

Python
msg="Python is awesome!"defdisplay():print("Inside function:",msg)display()print("Outside function:",msg)

Output
Inside 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.

Python
deffun():print("Inside Function",s)# Global scopes="I love Geeksforgeeks"fun()print("Outside Function",s)

Output
Inside 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:

Python
deffun():s="Me too."print(s)s="I love Geeksforgeeks"fun()print(s)

Output
Me 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:

Python
deffun():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:

Python
deffun():globalss+=' GFG'# Modify the global variableprint(s)s="Look for Geeksforgeeks Python Section"print(s)s="Python is great!"fun()print(s)

Output
Python 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.

Python
a=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)

Output
global: 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 basisGlobal VariableLocal Variable
DefinitionDeclared outside the functionsDeclared within the functions
LifetimeThey are created  the execution of the program begins and are lost when the program is endedThey are created when the function starts its execution and are lost when the function ends
Data SharingOffers Data SharingIt doesn't offers Data Sharing
ScopeCan be access throughout the codeCan access only inside the function
Parameters neededParameter passing is not necessaryParameter passing is necessary
Storage A fixed location selected by the compilerThey are  kept on the stack
ValueOnce the value changes it is reflected throughout the codeonce changed the variable don't affect other functions of the program

Global Variables in Python
Visit Courseexplore course icon
Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp