Python variables local to function

How to declare global variables in Python

In this tutorial we will learn about different terminologies related to declaring variables (local and global) in Python. You need to be familiar with namespace, scope and functions to be able to declare local and/or global variables in python scripts. We will cover these in details, I will try to give as much as details as possible to help even a beginner understand the basic concepts of Python programming.

Python version from my environment

# python3 --version Python 3.6.8

Define a function with def

  • You should be familiar with what are functions and how we can define a function in Python
  • Functions are the primary and most important method of code organization and reuse in Python.
  • As a rule of thumb, if you anticipate needing to repeat the same or very similar code more than once, it may be worth writing a reusable function.
  • Functions can also help make your code more readable by giving a name to a group of Python statements.
  • Functions are declared with the def keyword and returned from with the return keyword:
  • Python comes with multiple in-build functions
Читайте также:  Html window position center

In this example we have a simple function

# cat /tmp/define_functions.py #!/usr/bin/env python3 def do_nothing(): pass # Call the do_nothing function do_nothing()
  • Even for a function with no parameters like this one, you still need the parentheses () and the colon : in its definition
  • The next line needs to be indented, you cannot use TAB, use space character to indent the next line
  • Python requires the pass statement to show that this function does nothing. It’s the equivalent of This page intentionally left blank

I will execute this script

# python3 /tmp/define_functions.py

There is no output as expected.

Now we will print some thing on the screen

#!/usr/bin/env python3 def hello_world(): print('hello world') # Call the hello_world function hello_world()

The output from this script will execute the print() function:

# python3 /tmp/define_functions.py hello world

We will go one step ahead and use function to return boolean True/False value and further use this in if and else condition

#!/usr/bin/env python3 def agree(): return True if agree(): print('Good, you agree') else: print('I hope you agree next time')

The output from this script:

# python3 /tmp/define_functions.py Good, you agree

So I hope now since you have a basic idea of functions in Python

What are Namespaces and Scope in Python

  • Python programs have various namespaces sections within which a particular name is unique and unrelated to the same name in other namespaces
  • Each function defines its own namespace.
  • If you define a variable called x in a main program and another variable called x in a function, they refer to different things.
  • But the walls can be breached: if you need to, you can access names in other namespaces in various ways.
  • Functions can access variables in two different scopes: global and local.
  • An alternative and more descriptive name describing a variable scope in Python is a namespace.
  • Any variables that are assigned within a function by default are assigned to the local namespace.

We will understand about this better in next chapters and examples.

Declare Local Variable

  • A local variable’s identifier has local scope.
  • It’s «in scope» only from its definition to the end of the function’s block.
  • It «goes out of scope» when the function returns to its caller.
  • So, a local variable can be used only inside the function that defines it.

Let us take this simple python script

#!/usr/bin/env python3 def func(): # declare local variable inside the function a = [] for i in range(5): a.append(i) func() print(a)

Here when function func() is called the empty list » a » is created, five elements are appended, and then » a » is destroyed when the function exits.
The output of this script will fail to print content of variable » a «

# python3 /tmp/define_namespace.py Traceback (most recent call last): File "/tmp/define_namespace.py", line 9, in print(a) NameError: name 'a' is not defined

Declare Global Variable

  • Identifiers defined outside any function (or class) have global scope, these may include functions, variables and classes.
  • Variables with global scope are known as global variables.
  • Identifiers with global scope can be used in a .py file or interactive session anywhere after they’re defined.

We will use our existing example and declare a outside in the main script as global variable

#!/usr/bin/env python3 # declare global variable outside the function a = [] def func(): for i in range(5): # Access global variable inside the function a.append(i) func() print(a)

The output from this script will print the content of variable » a » as a was defined under global scope (outside function)

# python3 /tmp/define_variable.py [0, 1, 2, 3, 4]

Access and Modify Global Variable from a function

How to declare global variables in Python

  • In our last example we didn’t modified the value of the variable
  • By default, you cannot modify a global variable in a function , when you first assign a value to a variable in a function’s block, python creates a new local variable
  • For example in this sample python script, I have defined a global variable
  • Next I will access this variable inside access_global() function and print the value
  • Then I will modify the value of var from 10 to 20 inside modify_global_var() function
  • Later I will call modify_global_var() function to check the value of var variable
  • At the end I will again print the value of var to check if the content of global variable was modified

Now when we execute the script the local var shadows the global var inside modify_global_var() , making it inaccessible in the scope of the function’s block. But our last print function shows that variable var still exists and has its original value ( 10 ) after function modify_global_var() is executed.

# python3 /tmp/define_variable.py Value of var within function is: 10 New value of var after modification: 20 Original value of var is: 10

If you don’t use global within a function, Python uses the local namespace and the variable is local . It goes away after the function completes.

So to modify a global variable in a function’s block, you must use a global statement to declare that the variable is defined in the global scope:

How to declare global variables in Python

We will re-run this python script:

# python3 /tmp/define_variable.py Value of var within function is: 10 New value of var after modification: 20 Original value of var is: 20

So now the value of var is retained even after modify_global_var() function is executed

Python provides two functions to access the contents of your namespaces:

  • locals() returns a dictionary of the contents of the local namespace.
  • globals() returns a dictionary of the contents of the global namespace.

For example we have defined a new local variable for var within access_global() function and then use locals to print the available local variable

#!/usr/bin/env python3 # Define Global Variable var = 10 def access_global(): var=20 print('Value of var within function is: ', var) print('locals:', locals()) # Call access_global function access_global()

The output from this script

# python3 /tmp/define_variable.py Value of var within function is: 20 locals: 20>

Conclusion

So I hope you understood the difference between local and global variables. In this tutorial we learned about different terminologies from Python programming such as functions, namespaces, scopes and declaring variables.

The basic rule is that any variable which is assigned in the main script would be global variable while if it is assigned within the function then it would be considered as local variable unless you explicitly use global keyword

Lastly I hope this tutorial on variables, namespace and scope in Python programming was helpful. So, let me know your suggestions and feedback using the comment section.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Python Variable Scope

In Python, we can declare variables in three different scopes: local scope, global, and nonlocal scope.

A variable scope specifies the region where we can access a variable. For example,

def add_numbers(): sum = 5 + 4

Here, the sum variable is created inside the function, so it can only be accessed within it (local scope). This type of variable is called a local variable.

Based on the scope, we can classify Python variables into three types:

Python Local Variables

When we declare variables inside a function, these variables will have a local scope (within the function). We cannot access them outside the function.

These types of variables are called local variables. For example,

def greet(): # local variable message = 'Hello' print('Local', message) greet() # try to access message variable # outside greet() function print(message)
Local Hello NameError: name 'message' is not defined

Here, the message variable is local to the greet() function, so it can only be accessed within the function.

That’s why we get an error when we try to access it outside the greet() function.

To fix this issue, we can make the variable named message global.

Python Global Variables

In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

Let’s see an example of how a global variable is created in Python.

# declare global variable message = 'Hello' def greet(): # declare local variable print('Local', message) greet() print('Global', message)

This time we can access the message variable from outside of the greet() function. This is because we have created the message variable as the global variable.

# declare global variable message = 'Hello'

Now, message will be accessible from any scope (region) of the program.

Python Nonlocal Variables

In Python, nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.

We use the nonlocal keyword to create nonlocal variables.For example,

# outside function def outer(): message = 'local' # nested function def inner(): # declare nonlocal variable nonlocal message message = 'nonlocal' print("inner:", message) inner() print("outer:", message) outer()
inner: nonlocal outer: nonlocal

In the above example, there is a nested inner() function. We have used the nonlocal keywords to create a nonlocal variable.

The inner() function is defined in the scope of another function outer() .

Note : If we change the value of a nonlocal variable, the changes appear in the local variable.

Table of Contents

Источник

Global, Local and Nonlocal variables in Python

In this tutorial, let us learn the usage of Global, Local and Nonlocal variables in Python

F irst of all, I’m not the one on that image above. I’m just a benevolent writer who is here to talk about one of the most confusing concepts in Python programming “Global, Local and Nonlocal variables”. I know after reading the title you will be like “Why should I even worry about this”. Well, the answer is sometimes not knowing these teeny tiny itsy bitsy would cost you a lot. So without further ado, let’s get started.

In programming languages like C/C++, every time a variable is declared simultaneously a memory would be allocated this would allocation would completely depend on the variable type. Therefore, the programmers must specify the variable type while creating a variable. But luckily in Python, you don’t have to do that. Python doesn’t have a variable type declaration. Like pointers in C, variables in Python don’t store values legitimately; they work with references highlighting objects in memory.

Topics

The list of topics that would be covered in this article is given below:

  • Variables — A quick introduction
  • Global Variables — How to get rid of UnboundLocalError
  • Local Variables — How to get rid of NameError
  • Nonlocal Variables — When and how to use them

Also, before getting started I have to tell you one thing. The whole code of this article can be found in my GitHub Repository given below:

Источник

Оцените статью