{"id":51616,"date":"2023-06-05T06:21:42","date_gmt":"2023-06-05T06:21:42","guid":{"rendered":"https:\/\/www.askpython.com\/?p=51616"},"modified":"2023-06-05T07:15:15","modified_gmt":"2023-06-05T07:15:15","slug":"python-global-name-not-defined-error","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/python-global-name-not-defined-error","title":{"rendered":"Python &#8216;Global name not defined&#8217; Error and How to Handle It"},"content":{"rendered":"\n<p>Global in a general sense refers to something that is known all over the world. Global comes from the word globe, hence it means relating to the whole planet. In the scope of programming, a global variable refers to a variable that is not only known by its name inside a function but can be called from anywhere within a program. <\/p>\n\n\n\n<p>In contrast to local variables, which are specifically designed for use inside a particular code block or function, global variables (usually defined with the keyword global) can be referred to from anywhere in the code. <\/p>\n\n\n\n<p>The global name not defined error will pop up on your screen when the interpreter is trying to refer to a variable in the scope of the entire program and not limited to specific segments but couldn&#8217;t find any. <\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>In Python, a &#8216;Global name not defined&#8217; error occurs when the interpreter fails to find a global variable it&#8217;s trying to access. Global variables can be declared in two ways: outside a function, making it accessible throughout the program; or inside a function using the &#8216;global&#8217; keyword, making it usable beyond the function.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">Working with Global Variables in Python<\/h2>\n\n\n\n<p>A variable declared outside all function definitions is a global variable, meaning it&#8217;s accessible throughout the entire program, from any function or method. On the other hand, a variable declared inside a function is a local variable, and its scope is limited to that function alone.<\/p>\n\n\n\n<p>The concept of a global variable may be easier to understand with an example. Let&#8217;s say we have a variable, &#8216;<strong>count<\/strong>&#8216;, which is initialized with a value of zero. This variable is declared outside of all functions, making it a global variable. In a user-defined function, &#8216;<strong>increase_count<\/strong>()&#8217;, we&#8217;ll increment &#8216;count&#8217; by one each time the function is invoked.<\/p>\n\n\n\n<p>It&#8217;s important to note that if we want to modify a global variable within a function, we need to explicitly state that it is global using the &#8216;global&#8217; keyword. Without this keyword, the function will treat &#8216;count&#8217; as a local variable, and the changes will not reflect in the global scope.<\/p>\n\n\n\n<p>Let&#8217;s look at a Python code snippet demonstrating this:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n# declaring global variables\ncount=0\n\n# increasing the value inside our function\ndef increase_count():\n    global count\n    count = count + 1\n    return count\n\n# display the changed value in the scope of the function\nprint(increase_count()) # will print: 1\nprint(count) # will print: 1\n\n<\/pre><\/div>\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"492\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/image-1-1024x492.png\" alt=\"Image 1\" class=\"wp-image-52151\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/image-1-1024x492.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/image-1-300x144.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/image-1-768x369.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/image-1-1536x739.png 1536w, https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/image-1-2048x985.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Image 1<\/figcaption><\/figure>\n\n\n\n<p>In this example, we see that the &#8216;count&#8217; variable is declared globally (outside the function). Within &#8216;increase_count()&#8217;, we increment the value of &#8216;count&#8217; by one and return the new value. <\/p>\n\n\n\n<p>The <strong>global<\/strong> keyword before &#8216;count&#8217; in the function lets Python know that we mean the &#8216;count&#8217; variable that exists in the global scope, not a new, local &#8216;count&#8217; variable. Thus, the changes we make to &#8216;count&#8217; inside the function apply to the global &#8216;count&#8217; variable. Therefore, both print statements display the same value: 1.<\/p>\n\n\n\n<p><em><strong>Related: <a href=\"https:\/\/www.askpython.com\/python\/built-in-methods\/python-globals\" data-type=\"post\" data-id=\"7549\">Using the Python globals() function.<\/a><\/strong><\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Troubleshooting &#8216;Global name not defined&#8217; Errors in Python<\/h2>\n\n\n\n<p>&#8220;The global name not defined&#8221; is a Name error which can be caused due to various reasons. A couple of them are:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Local variable used as a global variable<\/strong>: If you forget to declare a variable as global inside a function and then try to access it outside the function, Python will raise a NameError. That&#8217;s because the interpreter will only search for the variable in the global scope, not finding it as it was defined only within the function.<\/li>\n\n\n\n<li><strong>Global variable not initialized<\/strong>: If a global variable has been declared using the global keyword inside a function, but it hasn&#8217;t been assigned a value, a NameError will occur. The Python interpreter requires that every variable referenced has a value assigned to it, including global variables.<\/li>\n<\/ol>\n\n\n\n<p>Let&#8217;s illustrate these cases with a couple of examples:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ndef increase_count():\n    # No global keyword before count, this will be a local variable.\n    local_count = 0\n    return local_count+1\n\nprint(increase_count())  # This will work fine and print 1\nprint(local_count)  # This will raise a NameError\n\n<\/pre><\/div>\n\n\n<p>In the first case, <strong>local_count<\/strong> is a local variable and is not defined in the global scope. Thus, when we attempt to print it outside of the function, we get a NameError.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ndef increase_count():\n    # Declared but not initialized.\n    global global_count\n    if global_count == 0:\n        return global_count+1\n\nprint(increase_count())  # This will raise a NameError\n\n<\/pre><\/div>\n\n\n<p>In the second case, we declare <code>global_count<\/code> as a global variable but don&#8217;t assign a value to it. Therefore, when the function tries to check <code>if global_count == 0<\/code>, it raises a NameError.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>To resolve &#8220;Global name not defined&#8221; error, ensure all variables are defined in the correct scope and properly initialized before they&#8217;re used. If a variable is meant to be global, use the <code>global<\/code> keyword within the function and assign a value to the variable. If the variable should only exist within a function, only reference it within that function.<\/p>\n<\/blockquote>\n\n\n\n<p><em><strong>Do check out: <a href=\"https:\/\/www.askpython.com\/resources\/disable-warnings-in-python\" data-type=\"post\" data-id=\"48885\">How to Disable a Warning in Python?<\/a><\/strong><\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<p>This article talks about what global variables are in Python. Global variables can be used in the scope of an entire program, be it inside or outside a particular block of code. There are a couple of ways to declare global variables and they have been discussed in the above sections. The name error associated with global variables is fairly simple to rectify. <em>What other differences do you think are there between local and global variables other than their scope of use?<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Global in a general sense refers to something that is known all over the world. Global comes from the word globe, hence it means relating to the whole planet. In the scope of programming, a global variable refers to a variable that is not only known by its name inside a function but can be [&hellip;]<\/p>\n","protected":false},"author":49,"featured_media":52097,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-51616","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/51616","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/49"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=51616"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/51616\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/52097"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=51616"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=51616"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=51616"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}