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
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
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'
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 |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
Naming rules
Here are a few things to keep in mind when coming up with names for your variables:
A name must be typed exactly the way it was originally typed. Names are case sensitive (
my_hobby
is a different name thanMY_HOBBY
).A good name is both descriptive but not overly descriptive.
my_hobby
is clear and descriptive,mh
is too short and mysterious, andmy_most_favorite_hobby_ever
is overly verbose.When a name is made up of multiple words, the Python convention is to separate each word with an underscore.
A name may contain numbers, but it cannot start with a number. It can either start with a letter or an underscore, but starting with an underscore actually has a special meaning we'll get into later.