{"id":74245,"date":"2019-12-14T10:10:45","date_gmt":"2019-12-14T04:40:45","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=74245"},"modified":"2024-08-22T17:54:45","modified_gmt":"2024-08-22T12:24:45","slug":"python-variable-scope","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/","title":{"rendered":"Python Variable Scope &#8211; Get set access variables"},"content":{"rendered":"<p>You might have encountered situations where you&#8217;re trying to access a variable, but the value is either different or doesn&#8217;t exist at all. This often happens because you\u2019re not familiar with variable scope. Don&#8217;t worry, we&#8217;ve got you covered. In this article, we will explore the scope of variables, different types of scope, and the keywords associated with Python variable scope.<\/p>\n<h3>What is Variable Scope in Python?<\/h3>\n<p>In programming languages, variables need to be defined before they can be used. The scope of a variable refers to the region of the code where the variable can be accessed. Think of it as a container or a block where the variable is recognized and can be manipulated. Outside of this block, the variable is not visible and cannot be accessed. Understanding variable scope is crucial for managing data and avoiding errors in your programs.<\/p>\n<h3>Types of Python Variable Scope<a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2019\/12\/Types-of-Python-Variable-Scope.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-74309 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2019\/12\/Types-of-Python-Variable-Scope.jpg\" alt=\"types of scope in python\" width=\"651\" height=\"341\" \/><\/a><\/h3>\n<p>There are four types of variable scope in Python, let\u2019s go through each of them.<\/p>\n<h4>1. Local Scope<\/h4>\n<p>Local scope variables can only be accessed within its <strong>block<\/strong>.<\/p>\n<p>Let\u2019s see it with an example.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">a = 10\r\ndef function():\r\n  print(\u201cHello\u201d)\r\n  b = 20\r\nfunction()\r\nprint(a)\r\nprint(b)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Hello<br \/>\n10<br \/>\nTraceback (most recent call last):<br \/>\n<b>\u00a0\u00a0<\/b>File &#8220;main.py&#8221;, line 7, in &lt;module&gt;<br \/>\n<b>\u00a0\u00a0\u00a0\u00a0<\/b>print(b)<br \/>\nNameError: name &#8216;b&#8217; is not defined<\/div>\n<p>In the above example, we see that Python prints the value of variable a but it cannot find variable b. This is because b was defined as a <strong>local scope<\/strong> in the function so, we cannot access the variable outside the function. This is the nature of the local scope.<\/p>\n<h4>2. Global Scope<\/h4>\n<p>The variables that are declared in the global scope can be accessed from anywhere in the program. Global variables can be used <strong>inside<\/strong> any functions. We can also change the global variable value.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">Msg = \u201cThis is declared globally\u201d\r\n\r\ndef function():\r\n  #local scope of function\r\n  print(Msg)\r\n\r\nfunction()<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">This is declared globally<\/div>\n<p>But, what would happen if you declare a local variable with the <strong>same name<\/strong> as a global variable inside a function?<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\"> msg = \u201cglobal variable\u201d\r\n\r\ndef function():\r\n  #local scope of function\r\n  msg = \u201clocal variable\u201d\r\n  print(msg)\r\n\r\nfunction()\r\nprint(msg)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">local variable<br \/>\nglobal variable<\/div>\n<p>As you can see, if we declare a local variable with the same name as a <strong>global variable<\/strong> then the local scope will use the <strong>local variable<\/strong>.<\/p>\n<p>If you want to use the global variable inside local scope then you will need to use the <strong>\u201cglobal\u201d<\/strong> keyword which we will discuss later in this article.<\/p>\n<h4>3. Enclosing Scope<\/h4>\n<p>A scope that isn\u2019t <strong>local<\/strong> or <strong>global<\/strong> comes under enclosing scope. This will be better understood with an example.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">def vehicle():\r\n  fun= \u201cStart\u201d\r\n  def car():\r\n    model= \u201cToyota\u201d\r\n    print(fun)\r\n    print(model)\r\n  car()\r\nvehicle()<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Start<br \/>\nToyota<\/div>\n<p>In the example code, the variable fun is used inside the <strong>car() function<\/strong>. In that case, it is neither a local scope nor a global scope. This is called the enclosing scope.<\/p>\n<h4>4. Built-in Scope<\/h4>\n<p>This is the <strong>widest scope<\/strong> in Python. All the reserved names in Python <strong>built-in modules<\/strong> have a <strong>built-in scope<\/strong>.<\/p>\n<p>When the Python doesn\u2019t find an identifier in it\u2019s local, enclosing or global scope, it then looks in the built-in scope to see if it\u2019s defined there.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">a = 5.5\r\nint(a)\r\nprint(a)\r\nprint(type(a))<\/pre>\n<p>Python would see in the local scope first to see which of the variables are defined in the local scope, then it will look in the enclosing scope and then global scope.<\/p>\n<p>If the identifier is not found anywhere then, at last, it will check the built-in scope.<\/p>\n<p>Here the functions <strong>int()<\/strong>, <strong>print()<\/strong>, <strong>type()<\/strong> does not need to be defined because they are already defined in the built-in scope of Python.<\/p>\n<h3>Global and Nonlocal keyword<\/h3>\n<p>Remember we talked about the problem \u201cWhat would happen if we declare variables with the same name in different scopes?\u201d For these type of situations, we have <strong>\u201cglobal\u201d<\/strong> and <strong>\u201cnonlocal\u201d<\/strong> keywords.<\/p>\n<p>Let\u2019s see how we can use them.<\/p>\n<h4>1. Global Keyword<\/h4>\n<p>Let\u2019s consider the example, in which we first see the problem<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">a = 100\r\ndef method():\r\n  a = 50\r\n  print(a)\r\nmethod()\r\nprint(a)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">50<br \/>\n100<\/div>\n<p>The above code will print the values 50 and 100 because in the local scope variable, a is referenced to 50 and outside the method() function, it is being referenced to the global variable.<\/p>\n<p>But, what if we wanted to access the global variable inside the<strong> method() function<\/strong>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">a = 100\r\ndef method():\r\n  global a\r\n  a = 50\r\n  print(a)\r\nmethod()\r\nprint(a)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">50<br \/>\n50<\/div>\n<p>Now we see that by using the global keyword, we can declare that we want to use the variable<strong> a<\/strong> which is defined in the global scope.<\/p>\n<p>So, when assigning the 50 to the variable, we also changed the value <strong>outside<\/strong> the function.<\/p>\n<h4>2. Nonlocal Keyword<\/h4>\n<p>Like the global keyword, we have a<strong> \u201cnonlocal\u201d<\/strong> keyword for times when we need to change a nonlocal variable.<\/p>\n<p>We will see the examples with and without a nonlocal keyword.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">a = \"global variable\"\r\ndef method():\r\n        a = \"nonlocal variable\"\r\n        def function():\r\n                a = \"local variable\"\r\n                print(a)\r\n        function()\r\n        print(a)\r\nmethod()\r\nprint(a)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">local variable<br \/>\nnonlocal variable<br \/>\nglobal variable<\/div>\n<p>In the <strong>function()<\/strong>, a is referring to <strong>\u201clocal variable\u201d<\/strong>, in <strong>method()<\/strong>, a is referring to <strong>\u201cnonlocal variable\u201d<\/strong> and <strong>outside<\/strong> these functions, a refers to <strong>\u201cglobal variable\u201d<\/strong>.<\/p>\n<p>Now we use the nonlocal variable.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">a = \"global variable\"\r\ndef method():\r\n        a = \"nonlocal variable\"\r\n        def function():\r\n                nonlocal a\r\n                a = \"local variable\"\r\n                print(a)\r\n        function()\r\n        print(a)\r\nmethod()\r\nprint(a)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">local variable<br \/>\nlocal variable<br \/>\nglobal variable<\/div>\n<p>We used the nonlocal keyword on \u201ca\u201d variable <strong>inside<\/strong> the <strong>function()<\/strong>.<\/p>\n<p>This is why when we changed the nonlocal variable value it also changed the value of \u201ca\u201d variable that is defined in <strong>method() function<\/strong>.<\/p>\n<h3>Summary<\/h3>\n<p>This was everything about the Python variable scope.<\/p>\n<p>We understood the <strong>variable scope<\/strong> and its <strong>multiple types<\/strong> where we saw how the same name can have <strong>different values<\/strong> in <strong>different scope<\/strong>.<\/p>\n<p>In the later part, we saw how you can use <strong>global<\/strong> and <strong>nonlocal keywords<\/strong> to solve the problem of having <strong>different values<\/strong> under the <strong>same variable name<\/strong>.<\/p>\n<p>I hope TechVidvan&#8217;s Python variable scope article was helpful to you.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>You might have encountered situations where you&#8217;re trying to access a variable, but the value is either different or doesn&#8217;t exist at all. This often happens because you\u2019re not familiar with variable scope. Don&#8217;t&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":74294,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1053],"tags":[1083,1084,1085,1086,1087,1088],"class_list":["post-74245","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-global-scope-in-python","tag-local-scope-in-python","tag-python-enclosing-scope","tag-python-variable-scope","tag-scope-of-variables-in-python","tag-types-of-python-variable-scope"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Variable Scope - Get set access variables - TechVidvan<\/title>\n<meta name=\"description\" content=\"Python variable scope - Learn what is the scope of variables in Python, types of scope in Python, as well as, global and nonlocal keywords in Python.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Variable Scope - Get set access variables - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Python variable scope - Learn what is the scope of variables in Python, types of scope in Python, as well as, global and nonlocal keywords in Python.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2019-12-14T04:40:45+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-08-22T12:24:45+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-variable-scope.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Variable Scope - Get set access variables - TechVidvan","description":"Python variable scope - Learn what is the scope of variables in Python, types of scope in Python, as well as, global and nonlocal keywords in Python.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/","og_locale":"en_US","og_type":"article","og_title":"Python Variable Scope - Get set access variables - TechVidvan","og_description":"Python variable scope - Learn what is the scope of variables in Python, types of scope in Python, as well as, global and nonlocal keywords in Python.","og_url":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2019-12-14T04:40:45+00:00","article_modified_time":"2024-08-22T12:24:45+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-variable-scope.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Python Variable Scope &#8211; Get set access variables","datePublished":"2019-12-14T04:40:45+00:00","dateModified":"2024-08-22T12:24:45+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/"},"wordCount":899,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-variable-scope.jpg","keywords":["global scope in python","local scope in python","python enclosing scope","Python Variable Scope","scope of variables in python","types of python Variable scope"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/","url":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/","name":"Python Variable Scope - Get set access variables - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-variable-scope.jpg","datePublished":"2019-12-14T04:40:45+00:00","dateModified":"2024-08-22T12:24:45+00:00","description":"Python variable scope - Learn what is the scope of variables in Python, types of scope in Python, as well as, global and nonlocal keywords in Python.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-variable-scope.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2019\/12\/python-variable-scope.jpg","width":802,"height":420,"caption":"scope of variables in Python"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/python-variable-scope\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Python Variable Scope &#8211; Get set access variables"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/74245","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=74245"}],"version-history":[{"count":1,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/74245\/revisions"}],"predecessor-version":[{"id":447670,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/74245\/revisions\/447670"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/74294"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=74245"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=74245"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=74245"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}