Variables

In Python, everything is an object. Variables are names given to identify these objects. In other words, a variable can be thought of as a “label” or “name tag” for Python objects that we’re working with. With any good labelling system, it makes it easy to retrieve the right object that we’re looking for.

Example of a Variable

The easiest way to understand a variable is to see how it’s used in the wild.

Let’s say we have an oven that measures temperature in Celcius, but all of our recipes are in Fahrenheit. We’re baking cookies and it says to pre-heat the oven to 350 degrees Fahrenheit. We’ll need to convert this to Celcius using this calculation:

\(T-32 \times \frac{5}{9}\)

where T is the temperature in Fahrenheit.

(350-32)*(5/9)
176.66666666666669

To make the code more clear, we can store temperature as a variable, called temperature_in_fahrenheit.

temperature_in_fahrenheit = 350

(temperature_in_fahrenheit-32)*(5/9)
176.66666666666669

Creating a Variable

We can create a variable by assigning it a value.

x = 10
print(x)
10

In the example above, variable x is assigned the value 10. We can treat x as if it were 10 and apply arithmetic operations to it.

print(x*2)
print(x+100)
20
110

We can re-assign a variable to another value even after it’s already been assigned once. When we use the variable after re-assignment, the new value will referenced. The initial value is no longer stored.

x = 1
print(x)
print(x*2)
print(x+100)
1
2
101

We can also re-assign a variable to a value of another datatype. In doing so, we are changing the datatype of the variable.

a = 10
print(f"Datatype of {a}: {type(a)}")

a = "helloworld"
print(f"Datatype of {a}: {type(a)}")
Datatype of 10: <class 'int'>
Datatype of helloworld: <class 'str'>

Chain Assignment

With chain assignment, you can assign the same value to several variables simultaneously. Let’s assign a, b, and c to 100.

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

a, b, and c are 3 variables that all have the same value 100.

Variable Assignment and Objects in Python

In Python, it’s important to note that everything is an “object”. Integers, strings, and floats are treated as objects. So a variable is a symbolic name that is a reference to an object (value). Once an object (value) is assigned to a variable, you can refer to the object by that name. Let’s look at an example.

x = 500

This assignment creates an integer object with the value 500 and assigns the variable x to point to that object.

Now, let’s say we want to create a new variable y that points to x.

y = x 
y
500

Assigning one variable to another does not create a new object. Instead, it creates a new symbolic reference, y, which points to the same object that x points to. What happens when we re-assign x to another value?

x = 111

A new integer object gets created with the value 111 and x becomes a reference to it. The value of y is still referencing the original value that x was assigned to.

y
500

Global and Local Variables

A global variable is defined outside a function and can be accessed inside any function within your Python environment. Let’s create a variable called w. It’s a global variable because it’s defined outside of a function.

w = 'hi!'
w
'hi!'

We can access w inside a function. Let’s create a function that prints w.

def print_greetings():
    print(w)
    
print_greetings()
hi!

If a variable is defined inside a function, it’s called a local variable and can only be accessed inside that function.

def print_greetings():
    w = 'hola!'
    print(w)

print_greetings()
hola!

We created a local w variable inside our function print_greetings. This takes priority over the outside global variable. That’s why the value of local variable w gets printed (“hola!”) instead of the global variable value (“hi!”).

That being said, if we were to print w on its own, it will refer to the global variable rather than the local variable. This is because the local variable cannot be accessed outside of the function that it’s defined in.

print(w)
hi!

Variable Naming

When writing a Python script or application, it’s important to give your variable a descriptive name. This is especially true for data science projects where the name of your variable can give more information on its purpose at first glance.

Here are some general rules about variable naming in Python:

  • In Javascript, variables tend to follow the camelCase convention. In Python, we use snake_case where every word is separated with an underscore.

  • Variables can contain digits but the first character of a variable name cannot be a digit. For example, a2 is a legitimate variable name but 2a would raise an error.

  • Variable names are case-sensitive so you can create two variables with the same spelling but if they have different lower-case/upper-case letters, they will be treated as two separate variables. The general trend is to keep your variable names lower-case (i.e., use age instead of Age).

age = 10
Age = 50

print(f"age: {age}, Age: {Age}")
age: 10, Age: 50

In Python, there are several keywords that are restricted from being used as variable names. These should never be used as variable names. You can check out the reserved keywords below:

help("keywords")
Here is a list of the Python keywords.  Enter any keyword to get more help.

False               break               for                 not
None                class               from                or
True                continue            global              pass
__peg_parser__      def                 if                  raise
and                 del                 import              return
as                  elif                in                  try
assert              else                is                  while
async               except              lambda              with
await               finally             nonlocal            yield

Variable naming is partly a style preference, but there are suggested guidelines to follow in Python’s official Style Guide. You can check out the suggestions here.