4 min read

Understanding Variables in Python 3

Learn to declare and use variables in Python 3. Learn to assign values to multiple variables and benefits of the global keyword.
Understanding Variables in Python 3

Topics Covered

  1. What is a Variable in Python?
  2. How to find the type of a variable in Python?
  3. How to assign values to multiple variables in Python?
  4. Variable Assignment - What happens behind the scenes?
  5. How to output variables in Python?
  6. What are global variables in Python?
  7. Right ways to Declare Variables
  8. Exercises to solve

What is a Variable in Python?

A Python variable is a reserved memory location that stores values.

Python is a dynamically typed language. Unlike statically typed languages like C and C++, the data type of a variable in Python is defined at runtime. Hence, the variable type can change during the code lifetime.

This is different for statically typed languages, where you have to declare a variable with a specific data type, and values assigned to it during its lifetime must always have the same type. For example, in C or C++.

Copy-paste the below code into your IDE and watch how the data types of variable x changes during the execution of code.

Code

# Store a string
x = "Pylenin"
print(x)

# Store an integer
x = 10
print(x)

# Store a float
x = 3.5
print(x)

# Store a list
x = [1, 2, 3]
print(x)

Output

Pylenin
10
3.5
[1, 2, 3]


How to find the type of a variable in Python?

You can use the type() function to get the data type of a variable in Python.

Code

x = "Pylenin"
print(type(x))

Output

<class 'str'>

How to assign values to multiple variables in Python?

In Python, you can also perform chained assignments, which makes it possible to assign the value(s) to multiple variables simultaneously:

Code

x = y = z = 100
print(x, y, z)

Output

100, 100, 100

You can also assign different values to different variables.

Code

x, y, z = 1, 2, 3
print(x)
print(y)
print(z)

Output

1
2
3

Variable Assignment - What happens behind the scenes?

x = "Pylenin"

When you make the above assignment, Python creates a string object and assigns the variable x to point to the string object.

Code

x = "Pylenin"
print(type(x))

Output

<class 'str'>

Now what happens, if you run the following code?

Code

x = "Pylenin"
print(type(x))

y = x

Now there is another variable y in our code and that is set equal to x.

When you run the code, Python won’t create a new variable. It will create a symbolic reference y that points to the same string object.

You can confirm this by finding the id of both variables. Whenever an object is created in Python, it is assigned a unique identity. You can find the id of variables, by using the id() built-in function.

Code

x = "Pylenin"
print(type(x))

y = x
print(id(y), id(x))

Output

<class 'str'>
1957481302640 1957481302640

As you can see, both x and y have the same id.


How to output variables in Python?

In Python 3, you can use the print() function to output variables to the output of choice. Learn more about the various use cases of print in Python.

Check out this example of outputting to standard output.

Code

name = "Pylenin"
print(name, "loves Python")

Output

Pylenin loves Python

You can also use the + operator to add variables. It is also called Concatenation when the data type is a string type.

Code

name = "Pylenin"
verb = "loves"
subject = "Python"
print(name+verb+subject)

Output

PyleninlovesPython

Note:- When you add variables the above way, no space is added between the variables.

While using the + operator to add variables, use variables of the same data type. Otherwise, Python will throw an error.

Code/Output

name = "Pylenin"
number = 10
print(name+number)

>>> Traceback (most recent call last):
  File "<some_file_name>", line 3, in <module>
    print(name+number)
TypeError: can only concatenate str (not "int") to str

What are global variables in Python?

Variables that are defined outside a function and in the outermost scope of your code are called Global variables.

Code

name = "Pylenin"

def job():
    work = "Data Engineer"

In the above example, the variable name is defined as a global variable. However, the variable work inside the job() function is a local variable to the function.

If you try to access a local variable outside the function, Python will throw an error.

Code/Output

name = "Pylenin"

def job():
    work = "Data Engineer"

print(work)

>>>Traceback (most recent call last):
     File "<some_file_location>", line 6, in <module>
    print(work)
NameError: name 'work' is not defined

In order to avoid this error, you have to declare the variable as global. You can do that by using the global keyword.

Code/Output

name = "Pylenin"

def job():
    global work
    work = "Data Engineer"

job()
print(work)

>>> Data Engineer

Right ways to Declare Variables

Rules to remember while declaring variables
  1. They can be a combination of lowercase and uppercase letters (A to Z), numbers (0 to 9) and underscore(_).
    Valid Examples - x, my_list, str123
  2. Identifiers cannot start with a number.
    Invalid example - 1name
    Valid Example - name1
  3. Reserved keywords in Python cannot be used as identifiers.
  4. Special symbols like !, @, #, $, % etc. cannot be used.
    x@ = 1
    >>> SyntaxError: invalid syntax
    

Examples of Valid Variables

  1. myvar1
  2. myvar_1
  3. _myvar1
  4. _1_myvar

Examples of Invalid Variables

  1. @myvar1
  2. 1myvar
  3. 1_myvar
  4. myvar@1

Exercises to Solve

  1. Create a variable called name and assign your own name to it. Print your name.

  2. Consider the following statements in Python. Do they change the value of x?

    x = "Pylenin"
    y = "loves"
    z = x
    z = 24
    
  3. The following code throws an error. Inspect the code and fix it.

    def planet():
        entity = "living things"
    print(entity)
    

Tweet me your answer!