Variables in Python: What Are They and Their Types

Reading Time: 7 Minutes
Publication date:
Last updated:

How to Store Data in Python for Easy and Efficient Access

If you open any program in Python, you’ll likely see many similarities:

x = 4
name = 'Victoria'
coin_flipping_result = ['Eagle', 'Heads', 'Heads', 'Eagle']

These are all variables. Programmers use variables to store data in the computer’s memory and perform various operations with it. This is where our story begins.

What is a Variable in Python?

A variable is a part of the computer’s memory that has a name. Structurally, it consists of three parts:

  • Name, or Identifier: This is the name created by the programmer to reference the variable. In the examples above, these are x, name, and coin_flipping_result.
  • Value: This is the information stored in the computer’s memory that the program works with. In the examples above, these are 4, 'Victoria', and ['Eagle', 'Heads', 'Heads', 'Eagle']. They are always members of some data type.
  • Address: This is the cell number in the computer’s memory where the variable’s value is stored.

Consider a vivid example. Imagine a large industrial warehouse filled with shelves, on which boxes are placed. The warehouse is the computer’s general memory. Suppose there’s a box placed on the second shelf of the third rack, in the sixth cell. If you put something in it and label it — the box is a variable. Whatever is inside is its value; the third rack, second shelf, and sixth cell is its address, and the label is its name.

How to Name Variables

When creating variables in Python, programmers follow some naming rules:

  • The first character must be an uppercase or lowercase Latin letter or an underscore _.
  • Subsequent characters can be uppercase or lowercase Latin letters, underscores, or digits.
  • Spaces cannot be used.
  • The variable’s name should not match any reserved keyword in Python.

Here are some examples:

  • Valid variable names: x, X, xyz, _x_y_z, XYZ, xyz_123, _123, x1Y2z2.
  • Invalid variable names: 1, 1x, x y z, x&y.

Python is case-sensitive, so name and Name will be considered different variables.

Although you can name variables with the names of standard library functions, it is not advisable as it will interfere with accessing those functions:

print('Hello, world!')
>>> Hello, world!
print = 14
print('Hello, world')
>>> TypeError: 'int' object is not callable

We’ll explain why this happens shortly.

Variable Naming Styles

Python syntax allows for various naming styles:

  • lowercase — all letters are lowercase;
  • lower_case_with_underscores — all letters are lowercase, words are separated by underscores;
  • UPPERCASE — all letters are uppercase;
  • UPPER_CASE_WITH_UNDERSCORES — all letters are uppercase, words are separated by underscores;
  • CamelCase — each word starts with an uppercase letter;
  • mixedCase — each word starts with an uppercase letter except for the first word;
  • Camel_Case_With_Underscores — each word starts with an uppercase letter, words are separated by underscores (this is unsightly, never do this).

However, among Python developers, the PEP 8 standard is accepted – a guide that provides recommendations for formatting code. This means the community has established additional restrictions for naming variables:

  • Use lowercase, separating words with underscores if necessary for readability.
  • If a mixedCase is prevalent in an existing project, write in the same style to maintain backward compatibility.
  • Avoid names like l (small L), O (capital O), and I (capital I) — in some fonts, they are indistinguishable from zero and one.

Following PEP 8 ensures your code is easy to understand and maintain.

Declaring and Assigning Values to Variables in Python

Python is a dynamically-typed language, meaning values are assigned to variables at runtime, not at compile time.

Thus, there’s no need to declare a variable separately — just initialize it by assigning a value. The equal sign = is used for this.

Even later, the same variable can be assigned values of different types:

x = 4
print(x)
# Output: 4
x = 'Word'
print(x)
# Output: Word

In statically-typed languages like C++ and Java, this action is impossible: the compiler would report an error because the variable originally stored an integer, not a string. But in Python, this is possible because variables refer to memory addresses rather than directly to data.

How Variable Initialization Works

In Python, all data is represented as objects. Each has an identifier – the address of the memory area where it is located.

This identifier can be known using the id() function:

x = 4
print(id(x))
# 2056817043856

When we initialized x, the program created an object containing the number 4, which belongs to the int data type.

Meanwhile, the variable itself does not contain the object but its address. This can be easily verified by creating another variable with the same four:

y = 4
print(id(y))
# 2056817043856

This means one object, one address, but two variables referring to it.

At any moment, we can assign a new value to a variable, which will then point to another object:

x = 1.2
y = 'String'

Now x and y point to different objects, with different addresses. And since no other variable points to the object at the previous address, it will be automatically deleted by the garbage collector.

Multiple Value Assignment

When you need to assign the same value to multiple variables, you can do so in one line using the following structure:

x = y = z = 4

Check this:

print(x, y, z)
# Output: 4 4 4

There is also a way to assign different values:

x, y, z = 1, 'Traveler', ['List', 'with', 'Strings']
print(x, y, z)
# Output: 1 Traveler ['List', 'with', 'Strings']

Importing Variables

If you need to import a variable from another file, use the following structure: from <filename> import <variable name>.

For example, we have a file named variables1.py:

name = 'Victoria'
age = 23
city = 'Delhi'

In the variables2.py file, use the name variable:

from variables1 import name
print(name)
# Output: Victoria

In this case, other variables are not accessible:

from variables1 import name
print(age)
# Error: NameError: name 'age' is not defined

To import multiple variables, list them separated by commas:

from variables1 import name, age
print(name, age)
# Output: Victoria 23

To import all objects, place an asterisk (*) after import:

from variables1 import *
print(name, age, city)
# Output: Victoria 23 Delhi

Deleting Variables

To delete a variable, use the del keyword:

x = 4
del x
print(x)
# Error: NameError: name 'x' is not defined

Types of Variables in Python

In Python, all variables exist within specific visibility scopes. There are three types:

  1. Local — within a function.
  2. Global — within the entire program (py-file).
  3. Nonlocal — within two nested functions (inner and outer).

Variables that fall under a specific scope form the namespace of that scope.

Local Variables

Any variables declared inside a function exist only within that function. For example:

def local_namespace():
    x = 4
    x = x ** 2
    return x
print(local_namespace())
>>> 16

We can manage x — change its value, perform operations, return it — but only within the local_namespace() function. If we try to access x elsewhere, the interpreter won’t recognize it:

def local_namespace():
    x = 4
    x = x ** 2
    return x
print(x)
>>> NameError: name 'x' is not defined

Conversely, a function can only manage variables declared within it:

x = 4
def local_namespace():
    x = x ** 2
    return x
print(local_namespace())
>>> UnboundLocalError: local variable 'x' referenced before assignment

However, a function can read global variables — it just can’t modify them:

x = 4
def local_namespace():
    y = x ** 2
    return y
print(x)
print(local_namespace())
>>> 4
>>> 16

Lastly, multiple variables with the same name can exist within the same program, provided they are in different namespaces:

x = 0
def local_namespace():
    x = 4
    x = x ** 2
    return x
print(x)
print(local_namespace())
>>> 0
>>> 16

Global Variables

Any variable declared outside functions is global and exists in the namespace of the entire py-file.

As shown above, it can be accessed within a function but cannot be modified unless specified using the global keyword:

x = 4
def local_namespace():
    global x
    x = x ** 2
    return x
print(local_namespace())
>>> 16

If we create a new variable inside a function, we can make it global using the global keyword:

def local_namespace():
    global x
    x = 4
    return x
print(local_namespace())
print(x)
>>> 4
>>> 4

Nonlocal Variables

Nonlocal variables are used when one function is nested within another and include only the namespaces of these two functions.

They are created using the nonlocal keyword:

def nonlocal_namespace():
    x = 4
    def local_namespace():
        nonlocal x
        x = x ** 2
        return x
    return local_namespace()
print(nonlocal_namespace())
>>> 16

Similarly, we cannot access nonlocal variables from the global scope:

def nonlocal_namespace():
    x = 4
    def local_namespace():
        nonlocal x
        x = x ** 2
        return x
    return local_namespace()
print(x)
>>> NameError: name 'x' is not defined

Checking Variable Existence

Python provides the globals() and locals() functions. They return a dictionary with the global and local symbol tables, including data about variables.

The keys in these dictionaries are the names of the variables as strings — this way, you can check their existence:

name = 'Victoria'
if 'name' in globals():
    print(True)
# Output: True

Similarly, you can get the value of a variable by its name from this dictionary:

name = 'Victoria'
if 'name' in globals():
    print(globals().get('name'))
# Output: Victoria

The same can be done within the local scope:

def local_namespace():
    name = 'Victoria'
    if 'name' in locals():
        print(locals().get('name'))
local_namespace()
# Output: Victoria

Maximum Possible Value of Variables

In Python, there is no special data type for storing large numbers. All integers belong to the int class, and all floating-point numbers belong to the float class.

Moreover, these classes have no bounds. A variable of any type can take on any large value as long as there is enough memory in the computer.

Printing Single and Multiple Variables

To print, use the print() function in Python. You can print a single variable or multiple variables separated by commas:

name, age, city = 'Victoria', 23, 'Delhi'
print(name)
print(name, age, city)
# Output:
# Victoria
# Victoria 23 Delhi

There are several ways to format the printing of variables in Python, but the most convenient is f-strings. Pass a string to the print function prefixed with the letter f. Variables are placed inside braces: {variable_name}.

name, age, city = 'Victoria', 23, 'Delhi'
print(f'Name: {name}. Age: {age}. City: {city}.')
# Output: Name: Victoria. Age: 23. City: Delhi.

Final Summary

  • In Python, variables are created with names and values. They store not the value itself but a link to its address in memory.
  • Naming variables involves using digits (not as the first character), Latin letters, and underscores.
  • There’s no need to declare a variable separately in Python — just assign a value to it directly. Multiple variables can be created in a single line.
  • They exist within a specific scope. Variables can be global (within the entire program), local (within a function), and nonlocal (between two nested functions).
  • Python variables have no size limit — they can be as large as the available memory on the device.
  • They can be imported from other files, deleted, checked for existence, and printed in formatted strings.

5 / 5. 2

Share:

Leave a comment