topics content@scaler.com
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- canonical_url: https://www.scaler.com/topics/difference between local and global variable in python/ title: What is the difference between local and global variable in python? | Scaler Topics description: Learn the difference between local and global variable in python on Scaler Topics. category: Python author: Tarandeep Singh --- :::section{.main} ## What is the Difference Between Local and Global Variable in Python? Variables have a very important role in storing data and information. Before discussing the Difference Between Local and Global Variable in Python, let's see what the scope of variable really is. ### Scope of Variable A variable's scope is basically the lifespan of that variable. It is the section of code to which a variable is alive. Depending on their scope, variables are divided into: * Global variables * Local variables `Local variables` can only be accessed within the function or module in which they are defined, in contrast to global variables, which can be used throughout the entire program. In Python, Global variable can be defined using `global` Keyword, also we can make changes to the variable in local context. There are some key Difference Between Local and Global Variable in Python: * `Global variables` are declared outside the functions whereas local variables are declared within the functions. * `Local variables` are created when the function starts its execution and are lost when the function ends. Global variables, on the other hand, are created as execution of the program begins and are lost when the program is ended.  * In contrast to global variables, local variables do not offer data sharing. * While global variables are kept in a fixed location selected by the compiler, local variables are kept on the stack. * For local variables, parameter passing is necessary, but not for global variables. * In Python, Global variables can be defined using `global` Keyword whereas local variables can be defined directly. ::: <!-- What is the main difference between local and global variables in Python? A) Global variables are declared within the functions whereas local variables are declared outside the functions. B) Local variables are created when the program starts its execution and are lost when the program is ended. Global variables, on the other hand, are created as the function starts its execution and are lost when the function ends. C) Local variables offer data sharing whereas global variables do not. D) Local variables are kept in a fixed location selected by the compiler, whereas global variables are kept on the stack. Answer: B) Local variables are created when the function starts its execution and are lost when the function ends. Global variables, on the other hand, are created as the program starts its execution and are lost when the program is ended. --> :::section{.main} ## Local Variable Local variables are declared inside the function blocks. In Python, local variables can be declared at any location in the code block. Only statements that are written inside a function can access local variables. They are secure in the way that no other function or variable of that program can access them. Local variables are created during the execution of the function  and are destroyed once the block has finished. As soon as the execution leaves the block in which a local variable is declared, it loses its content. It happens because local variables are always stored on the stack.  ### Example: Let's see a short example of how local variables can be defined. ```python::https://www.scaler.com/topics/python/online-python-compiler/?content_slug=1011e655bc90b9ce7bc6 def fun(): a = 10 print(a) fun() ``` ### Output: ```plaintext 10 ``` ::: :::section{.main} ## Global Variable `Global variables` are the types of variables that are declared outside of every function of the program. The global variable, in contrast to local variables, is accessible by all functions in a program. Global variables are not very reliable because any function in the program can alter their value. They continue to exist until the entire program has been ended. Global variables hold onto their values throughout the program execution. The compiler-determined fixed region of memory where they are stored is the cause. A global variable is useful when many functions are using the same set of data. Utilizing a lot of global variables could be challenging because they could undergo unwanted changes in value. ### Example: Let's see a short example of how global variables can be defined. Here, we are simply accessing the global variable using the global keyword. ```python::https://www.scaler.com/topics/python/online-python-compiler/?content_slug=f17351d4770c48c45c30 a = 10 def fun(): global a print(a) fun() ``` ### Output: ```plaintext 10 ``` ::: <!-- Which of the following statements about global variables is true? A) Global variables are only accessible by the function in which they are declared. B) Global variables are not reliable because they cannot hold onto their values. C) Global variables are stored in a compiler-determined fixed region of memory. D) Utilizing a lot of global variables can be challenging because they could undergo unwanted changes in value. Answer: C --> :::section{.main} ## Local Variable Vs. Global Variables Lets see the tabular difference Between Local and Global Variable in Python | Comparision Basis | Global Variable | Local Variable | |:---------------------------:|:------------------------------------------------------------------------------------------------------:|:------------------------------------------------------------------------------------------------------:| | Definition | Global variables are declared outside the functions | Local variables are declared within the functions | | Lifetime | Global variables are created as execution of the program begins and are lost when the program is ended | Local variables are created when the function starts its execution and are lost when the function ends | | Data Sharing | Global Variables Offers Data Sharing | Local Variables doesn't offers Data Sharing | | Scope | Accessible throughout the code | Accessible inside the function | | Storage | Global variables are kept in a fixed location selected by the compiler | Local variables are kept on the stack | | Parameter Passing | For global variables, parameter passing is not necessary | For local variables, parameter passing is necessary | | Changes in a Variable Value | Changes in a global variable is reflected throughout the code | Changes in a local variable doesn't affect other functions of the program | | Naming Restrictions | Global variables should be uniquely named i.e. many variables with the same name cannot exist. | Different variables with the same name can be declared in different functions. | | Memory | The global variable takes zero by default if it is not initialised. | If the local variable is not initialized, it defaults to a garbage value. | ::: <!-- Which of the following is a difference between Local and Global Variables in Python? A) Global variables are declared within the functions while local variables are declared outside the functions. B) Global variables are created when the function starts its execution and are lost when the function ends while local variables are created as execution of the program begins and are lost when the program is ended. C) Global variables offer data sharing while local variables do not offer data sharing. D) Local variables are accessible throughout the code while global variables are accessible inside the function. Answer: B --> :::section{.main} ## Examples to Understand Differences Between Local and Global Variable Let's see an example where we can more clearly understand the Difference Between Local and Global Variable in Python. ### Example of Local Variable: In this example, we are making a local variable inside the function and trying to access that local variable outside the function. ```python::https://www.scaler.com/topics/python/online-python-compiler/?content_slug=acd317b9e7346152415d def func(): a = 10 print(a) func() print(a) ``` ### Output: We can see that an error pops up while accessing the variable outside the function, as the scope of that variable is only up to that function. ```plaintext [NonZeroExitCode] Your code encountered a runtime error Traceback (most recent call last): File "main.py", line 5, in <module> print(a) NameError: name 'a' is not defined ``` ### Example of Global Variable: In this example, we are making a global variable and are trying to access that global variable inside and outside the function. ```python::https://www.scaler.com/topics/python/online-python-compiler/?content_slug=1312b236e2bcf08f0fd7 a=10 def func(): global a a+=10 print("Value inside the function:",a) func() print("Value Outside the function:",a) ``` ### Output: We can see that we can access the global variable both outside the function as well as inside the function. ```plaintext Value inside the function: 20 Value Outside the function: 20 ``` ::: :::section{.main} ## Advantages and Disadvantages of Global and Local variables We have discussed Difference Between Local and Global Variable in Python, now lets discuss about their advantages and disadvantages: ### Advantages of Local Variables * The main advantage of a local variable is that the data is not accidentally changed. Variable declared inside a function makes use of that variable while avoiding adverse side effects. * When the block containing the variable is executed, a local variable only uses memory for a brief period of time. ### Advantages of Global Variables * When dealing with multiple functions in the program that are manipulating the same data, global variables are very helpful. * The use of a global variable makes it simpler to make changes that are needed to be made throughout the entire programme. * For global variables, access is available from anywhere or via any program function at random. ### Disadvantages of Local Variables * The local variable's scope is restricted. * Local Variable prevents sharing of data. * Since local variables are created and destroyed with each entry and exit from the block, they cannot save the data in-between the function calls. ### Disadvantages of Global Variables * The use of numerous global variables may lead to the creation of programming errors. * The main issue it creates is the accidental changes in data that arise as a result of the program's multiple global variables. * It might also necessitate performing code refactoring, a time-consuming process that involves reorganizing the entire program's code. ::: :::section{.main} ## Which One is More Useful? In Python programming, both local and global variables are crucial when writing programs. However, many global variables could take up a lot of memory. It is getting harder to spot an undesireable change in global variables. As a result, it is wise to avoid declaring pointless global variables and using local variables for passing and manipulating data. It is generally good practice to make use of local variables in Python. ::: :::section{.summary} ## Conclusion * A reserved memory address for storing values is called a variable. A variable in a Python programme provides the computer with data to be processed. * Variables in Python have different scopes, representing their lifespan and access within the code. * Variables are divided into: * Global variables * Local variables * Local variables are created when a function starts and destroyed when it ends, while global variables are created when the program begins and lost when it ends. * Local variables can only be accessed within the function or module in which they are defined, in contrast to Global variables, which can be used throughout the entire program. * Local variables are declared inside the function blocks whereas Global variables are the type of variables that are declared outside every function of the program. * Local variables are stored on the stack, with their memory allocated and deallocated as functions are called and return. Global variables are stored in a fixed memory location determined by the compiler. * Local variables do not offer data sharing between functions, while global variables are accessible by multiple functions, enabling data sharing. * It is a good practice to use local variables to avoid unnecessary memory consumption and unintended changes in global variables. * When developing a programme in any language, both local and global variables are equally crucial. However, a sizable portion of the global variables could require a lot of RAM. :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully