2.3. Assignment#
Will Trimble and Amanda R. Kube Jotte
So far, we have seen that Python can evaluate mathematical expressions, but we haven’t used a equal sign. Python’s equal sign (=
) has different behavior for different data types. Some data types are immutable meaning that they can’t be changed or edited. Others are mutable and can be changed or edited. Mutable data types are more complicated and we will talk about them more in the next chapter. Immutable data types include integers, floats, booleans, strings (covered in the next section), and tuples (covered in the [next chapter](add link when we have it)).
When we “run” a Python cell containing an expression (ie a series of operations/comparisons on data without an =
), the expression is evaluated and the result is displayed.
1052.25 - 965 - 12.47 - 84.97 - 27.12 # Trying to balance checkbook
-37.31
Sometimes, instead of displaying the result, we would like to store it. We can store the result of any expression or function in a variable, which will allow us to access it later.
Storing a result entails giving it a variable name and using the assignment operator, a single =
. For immutable data types, an expression with a single equals will evaluate the right hand side and store the result in the variable name on the left hand side.
This cell subtracts a handful of numbers, creates a variable called balance
and stores the result in memory. We call a statement that stores a value in a variable an assignment statement. Note there is no output (ie nothing prints out below the code like it does for an expression).
balance = 1052.25 - 965 - 12.47 - 84.97 - 27.12 # This is an assignment statement
We can access and change the contents of balance
by invoking its name.
In any of the math expressions, balance
will be replaced by its value (-37.31).
balance # This is an expression (no =)
-37.31
balance - 17.21 + 2000 # Another expression
1945.48
Evaluating this expression does not change balance
.
balance
-37.31
I can use this value in comparisons as well. Is my balance greater than zero?
balance > 0 # This is also an expression
False
And balance
can be changed:
print(balance)
balance = balance + 40
print(balance)
-37.31
2.6899999999999977
Note that the value stored in balance
will change every time this cell is run.
print(balance)
balance = balance + 40
print(balance)
2.6899999999999977
42.69
Python variables are just names; they do not control the data types of the underlying data, and can store floats, integers, strings and other more complicated data types as well. Variable names in Python must begin with a letter, and can contain letters, numbers, and the underscore “_” character.
If I assign a variable twice, the later assignment overwrites the earlier value:
balance = 1052.25 - 965 - 12.47 - 84.97 - 27.12
balance = False
balance
False
What can we use this for? Everything. We will put every important piece of data into a variable whose name will hopefully allow humans to understand something about the variable’s content or purpose.
Some variables are temporary and will be discarded immediately; some we will assign, use once and forget about, and some variables may contain the key data and inferences.
elevation_ft = 577 # Lake Michigan-Huron above MSL
FEET_TO_METERS = 0.3048
elevation_m = elevation_ft * FEET_TO_METERS
elevation_m
175.86960000000002
Stay away from reserved words#
A small handful of short English words, called reserved words, are part of the Python language. These can’t be used as variable names:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
A similar list of names of built-in functions should also be avoided.
If you chose a variable name that is the same as a function that is already defined, you can accidentally replace the function with your variable, making the function unavailable.
For this reason, don’t use str
, int
, or float
as the name of your variables.
# Don't do this; int() won't work right after you overwrite it because it will be 6.
int = 6 # Don't call your variable int!!
int(56.3)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[11], line 3
1 # Don't do this; int() won't work right after you overwrite it because it will be 6.
2 int = 6 # Don't call your variable int!!
----> 3 int(56.3)
TypeError: 'int' object is not callable
# This cell restores the overwritten built-in function int
del(int) # This deletes the variable int from memory
int(12.3) # Now nothing is overwriting the int function
12
Assign variables before use#
Python will not use a default value for unassigned variables; if you use the name of a variable that has not been defined in the current Python session (ie the Python you have open right now), Python will throw an error:
january_balance
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[13], line 1
----> 1 january_balance
NameError: name 'january_balance' is not defined
What’s happening here? Python sees the variable name, searches its memory for a variable of that name, does not find one, and terminates with a red box labeled NameError
. This is the error for an undefined variable. It is the error that results from using a variable name that you haven’t defined yet or trying to access variables with misspelled names.
Now, you know how to write mathematical and boolean expressions and how to save the results of those expressions as variables. In the next session we are going to add a new data type to your repertoire: strings.