Python Variable – Define, Print, Scope, Delete, Best Practices

Python variable is an identifier to reference a value in the program. A variable contains the memory location of the object. They allow python program to access other objects and call their functions or perform other operations.


Rules to Define a Python Variable

There are few rules to define a python variable.

  1. Python variable name can contain small case letters (a-z), upper case letters (A-Z), numbers (0-9), and underscore (_).
  2. A variable name can’t start with a number.
  3. We can’t use reserved keywords as a variable name.
  4. Python variable can’t contain only digits.
  5. A python variable name can start with an underscore or a letter.
  6. The variable names are case sensitive.
  7. There is no limit on the length of the variable name.

Python Valid Variables Examples

  • abc
  • _: Yes, we can create a variable name as underscore.
  • __: Yes, multiple underscores are also a valid variable name.
  • x_yAB
  • _abc

Python Invalid Variable Examples

  • 9abc: variable name can’t start with a number.
  • 123: variable name can’t contain only numbers.
  • x-y: the only special character allowed in the variable name is an underscore.
  • def: invalid variable name because it’s a reserved keyword.

How to Declare a Variable in Python?

Python is a dynamically typed language. We don’t need to specify the type of variable when declaring it. The python variable is defined with equals sign. The left part contains the variable name and the right part contains the variable value.

Let’s look at some examples to declare a variable in Python.

x = 1  # number
s = "Hello"  # string
t = (1, 2)  # tuple
l = [1, 2, 3]  # list
d = {"1": "A", "2": "B"}  # dictionary

Python also supports multiple assignment. We can define multiple variables at once using multiple assignment.

a = b = c = 100
print(a, b, c)  # 100 100 100

We can also assign a sequence to a list of variables. In this case, the number of elements in the sequence must be equal to the number of variables.

a, b, c = 1, 2, "Hello"
print(a, b, c)  # 1 2 Hello

a, b, c = (1, 2, 3)
print(a, b, c)  # 1 2 3

a, b, c = [1, 2, 3]
print(a, b, c)  # 1 2 3

a, b, c = "098"
print(a, b, c)  # 0 9 8

Let’s see what happens when the number of variables and the number of elements in the sequence are not equal.

>>> a,b = (1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> 
>>> a,b,c,d = (1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 4, got 3)
>>> 

How to Print a Variable Value in Python?

We can use Python print() function to print the variable value. Let’s look at some examples to print variables values in Python.

x = 1  # number
print(x)
s = "Hello"  # string
print("s value is", s)
t = (1, 2)  # tuple
print("tuple value is", t)
l = [1, 2, 3]  # list
print(l)
d = {"1": "A", "2": "B"}  # dictionary
print("dict value is", d)
Python Variable Print
How to Print Python Variable Value

Python programs are executed sequentially. So if you try to access a variable before it’s defined, you will get NameError.

print(count)  # NameError: name 'count' is not defined

count = 100

print(count)  # 100

Best Practices for Python Variable Name

If you look at the above code snippets, the variable names are random. They don’t convey the meaning of the variables. There are few best practices to follow when naming a variable in Python.

  1. Use only small case letters, numbers, and underscores for python variable name.
  2. If the variable name has multiple words, you can separate them using an underscore.
  3. If the variable scope is private, then you can start its name with an underscore.
  4. You should avoid variable names starting and ending with underscores. They are used conventionally by Python built-in programs.
  5. Always use a meaningful name for the variable. It should convey the type of data and the intended use of the variable.
  6. The variable name length has no limit. But, it’s good to have small and meaningful names.

Based on the above best practices, we can change the above code snippet to have proper variable names.

count = 1
str_message = "Hello"
tuple_ints = (1, 2)
list_of_numbers = [1, 2, 3]
numbers_letters_dict = {"1": "A", "2": "B"}

How to Print the Type of Variable?

We don’t specify the type of variable in Python programs. We can use type() function to determine the type of the variable. Let’s look at some examples to print the type of variable.

count = 1  # number
print(type(count))
str_message = "Hello"  # string
print("str_message type is", type(str_message))
tuple_ints = (1, 2)  # tuple
print("tuple_ints type is", type(tuple_ints))
list_of_numbers = [1, 2, 3]  # list
print(type(list_of_numbers))
numbers_letters_dict = {"1": "A", "2": "B"}  # dictionary
print("numbers_letters_dict type is", type(numbers_letters_dict))

Output:

<class 'int'>
str_message type is <class 'str'>
tuple_ints type is <class 'tuple'>
<class 'list'>
numbers_letters_dict type is <class 'dict'>

What are the Different Types of Variable in Python

The type of the Python variable is the data type of its value. Python is an Object-Oriented programming language. Everything in Python is an object. So, python variables are always an instance of a class.

  • x = 1: Here the type of variable ‘x’ is ‘int’. It’s referring to an instance of class int.
  • message = “Hello”: The type of message variable is ‘str’.

Python Variable Scope

A variable scope defines the area of accessibility of the variable in the program. Python variables has two scopes.

  1. Local Scope
  2. Global Scope

Python Local Variable

When a variable is defined inside a function or a class then it’s accessible only inside it. They are called local variables and their scope is only limited to that function or class boundary.

If we try to access a local variable outside its scope, we get NameError that the variable is not defined.

Let’s understand the idea of python local variable with some examples.

def foo():
    foo_var = 1
    print(foo_var)


foo()
print(foo_var)
Python Local Variable Scope
Python Local Variable Scope
  • The print() inside the foo() function is able to access the foo_var because it’s inside its scope.
  • The print() outside the foo() function is not able to access the foo_var because it’s out of the scope of the variable.

Let’s look at another example for local variable defined inside a class. The variable scope is the class for this scenario.

class Foo:
    class_foo_var = 1

print(class_foo_var)

Output: NameError: name 'class_foo_var' is not defined


Python Global Variable

When the variable is not inside a function or a class, it’s accessible from anywhere in the program. These variables are called global variables. Let’s look at Python global variable examples.

global_msg = "Hello"


def foo():
    print(global_msg)  # global variables are accessible inside a function


class Foo:
    print(global_msg)  # global variables are accessible inside a class


if 5 < 10:
    print(global_msg)  # global variables are accessible inside a code block

The variables defined inside the code blocks such as if-else, for loop, while loop, try-except, etc. are added to the global scope, provided the code declaring the variable has been executed. Let’s understand this with a simple example.

>>> if True:
...     var_if = "if"
... else:
...     var_else = "else"
... 
>>> 
>>> print(var_if)
if
>>> print(var_else)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'var_else' is not defined
>>> 

The var_else is not defined because the code inside else block didn’t executed.

Let’s have a look at another example with try-except block.

>>> try:
...     var_try = "try"
...     raise TypeError('explicitly throwing')
... except:
...     var_except = "except"
... 
>>> print(var_try)
try
>>> print(var_except)
except
>>> 

We are able to access variables defined inside try and except block because they both got executed.


Deleting a Python Variable

We can delete a variable using del statement. Let’s look at a simple example to delete a python variable.

>>> count = 100
>>> print(count)
100
>>> del count
>>> 
>>> print(count)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'count' is not defined
>>> 

Python Static Variable

The variables defined inside a class can be accessed with the class name. They are also called static variables because they belong to the class.

class Data:
    id = 0


print(Data.id)  # static access

These variables can be access from the class object too. However, accessing statically using the class is the recommended way.

d1 = Data()

print(d1.id)  # class variable accessed from object

Quick word on globals() and locals() functions

  • Python globals() function returns the dictionary of current scope global variables.
  • Python locals() function returns the dictionary of current scope local variables.

We can use these functions at any code location to check if a variable is accessible at that place or not. They are built-in functions in Python.

Let’s look at some quick examples of these functions.

global_var = "global"

def foo():
    local_var = "local"
    print('global variables inside foo(): ', globals())
    print('local variables inside foo(): ', locals())


print('global variables: ', globals())
print('local variables: ', locals())
foo()

Output:

global variables:  {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x1006305f8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/hello_world.py', '__cached__': None, 'global_var': 'global', 'foo': <function foo at 0x1006817b8>}
local variables:  {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x1006305f8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/hello_world.py', '__cached__': None, 'global_var': 'global', 'foo': <function foo at 0x1006817b8>}
global variables inside foo():  {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x1006305f8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/hello_world.py', '__cached__': None, 'global_var': 'global', 'foo': <function foo at 0x1006817b8>}
local variables inside foo():  {'local_var': 'local'}
Python Global Local Variable Scope
Python Global and Local Variables

Python global keyword

We can access a global variable inside a function. But we can’t modify it. We have to use the global keyword to change the global variable value inside a function. Let’s understand this behavior with a simple example.

name = "Python"

def foo():
    print(name)

foo()
print(name)

# Output
# Python
# Python

Let’s see what happens when we try to modify the global variable value inside the function.

>>> name = "Python"
>>> def foo():
...     print(name)
...     name = "Java"
... 
>>> 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'name' referenced before assignment
>>> 
>>> print(name)
Python
>>> 

The reason is simple. When we are using assignment operator to change the value of “name”, it starts getting treated as a local variable. So accessing it inside the print() function is throwing because it’s not defined at that point.

Let’s use global keyword to modify the global variable value.

>>> name = "Python"
>>> 
>>> def foo():
...     global name
...     print(name)
...     name = "Java"
... 
>>> print(name)
Python
>>> foo()
Python
>>> print(name)
Java
>>> 

Python nonlocal keyword

The nonlocal keyword is used to access the variables defined outside the scope of the block. This is always used in the nested functions to access variables defined outside. The variables are always searched in the nearest enclosing scope excluding globals.

def outer_function():
    scope = "local"

    def inner_function():
        nonlocal scope
        scope = "nonlocal"
        print(scope)

    inner_function()
    print(scope)

Conclusion

Python variables are used in every program. They are a type of identifier. We learned how to define a variable, rules associated with it, and how to access and delete them. We also learned about variables scope – global and local.