Names & variables

Names

We very often want to re-use the same values multiple times in the same computer program - just imagine if we were writing a geometry program and needed to write the value of π to 50 digits every time we used it in a calculation!

To re-use a value, we just need to give it a name. Then, whenever we want to reference that value, we just reference the name instead.

One way to assign a name in Python is with an assignment statement. This statement assigns the name x to the value 7.

x = 7

The value could be any Python value, or it could even be an expression.

x = 1 + 2 * 3 - 4 // 5

A name that holds a piece of data is also known as a variable.

Using variables

The great thing about variables is that once they exist, we can reference them multiple times in our code!

Here's a short program to calculate the area and circumference of a circle:

pi = 3.1415926535
radius = 6
area = pi * (radius ** 2)
circ = 2 * pi * radius

🧠 Check Your Understanding

How many variables are in that program?

🧠 Check Your Understanding

How many times is the radius variable referenced?

Here's another program to do some string concatenation. And yes, it's a true story.

my_last_name = 'Fox'
partners_last_name = 'Gray'
daughters_last_name = partners_last_name + my_last_name

🧠 Check Your Understanding

What is my daughter's last name?

Re-assignment

A name can only be bound to a single value.

What do you think the following Python code will do?

my_name = 'Pamela'

my_name = my_name + 'ela'

🧠 Check Your Understanding

Your prediction:

In Python, re-assigning a name to a new value will replace the old value. However, Python evaluates the right-hand side of an assignment statement before the left-hand side, so when the right-hand side references the name, it will retrieve its current value, and then only once it's done computing the right-hand expression, it will re-assign the variable to the value of that expression.

Augmented assignment operators

It's actually incredibly common to re-assign a variable based on its previous contents, so common that Python and many other languages provide special operators to make it easier.

For example, instead of:

my_name = my_name + 'ela'

I could simply write:

my_name += 'ela'

That += operator means "take the previous value and add this new value to it".

This table summarizes all the special operators like that one:

Long version

Shortcut

x = x + 1

x += 1

y = y - 1

y -= 1

r = r * 2

r *= 2

w = w / 3

w /= 3

a = a // 4

a //= 4

p = p ** 2

p **= 2

Naming rules

Here are a few things to keep in mind when coming up with names for your variables:

🧠 Check Your Understanding

Which of these variable names should you avoid in Python?

➡️ Next up: Functions