Assignment#

Assignment for simple (immutable) data types#

We have seen that Python can evaluate mathematical expressions.

When we use Python interactively (typing one command at a time), when we “run” a cell the expression is evaluated and the result of the expression is displayed immediately.

For mathematical expressions, this is the result. Of course we see the answer, what else would anyone do with a computation?

# Trying to balance checkbook
1052.25 -965 -12.47 -84.97 -27.12
-37.31

Instead of displaying the result, we can store the result of any expression or function in a variable, which will allow us to access it (perhaps reading it, perhaps changing it or using it) later.

Storing a result entails giving it a variable name and using the assignment operator. In Python the assignment operator is the single equals sign =. For numeric and string 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. Note there is no output.

balance = 1052.25 -965 -12.47 -84.97 -27.12

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
-37.31
balance -17.21 + 2000
1945.48

Evaluating this expression does not change balance.

I can use this value in expressions.
Is my balance greater than zero?

balance > 0
False

And balance can be changed:

print(balance)
balance = balance + 40
print(balance)
-37.31
2.6899999999999977

Note that the value stored in balance changes every time this cell is run.

Python variables are just names. 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 = "Not enough" 
balance
'Not enough'

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.

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. Some variables will have the names of data files; some will have the values of parameters or options that change what the code does.

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 https://docs.python.org/3/library/functions.html 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[9], line 4
      1 # Don't do this; int() won't work right after you
      2 # overwrite it because it will be 6.
      3 int = 6   # don't call your variable int!!
----> 4 int(56.3)

TypeError: 'int' object is not callable
# This cell restores the overwritten builtin function int
del(int)
int(12.3)
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, Python will throw an error:

january_balance
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[11], 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 pink box labeled NameError. This is the error for an undefined variable, and this is the error that results from trying to access variables with misspelled names.

Assignment for mutable data types#

For mutable data types, = gives a new name to the same object. The data is not copied, and exists in only one place in the computer’s memory. Note this is not the same behavior as simple data types.

This may have unintended effects:

list1 = [1,2,3]
list2 = list1  # this does not create a new list
list1[2] = 6   # since there is only one list, changing list1
print(list1)
print(list2)   # changes list2.
[1, 2, 6]
[1, 2, 6]

If you need a second copy of a mutable object, you must copy it explicitly. Mutable data types have a .copy() method that will create a new copy that can be altered separately from the original:

list3 = [1,2,3]
list4 = list3.copy()
list3[2] = 8
print(list3)
print(list4)  
# Success!  list3 can finally have different values from list4
[1, 2, 8]
[1, 2, 3]

Immutable data types include strings, numbers, and tuples. Immutable data types and expressions copy by value. Mutable data types include lists, dictionaries, sets, and most more complicated data types. These require explicit copying.

Can you follow what is happening to the strings here?

animal1 = "dog"
animal2 = "cat"
animal3 = "procupine"
animal4 = animal3
animal3 = animal2
animal2 = animal1
animal1 = animal3 
# This line will display the contents of these four strings
animal1, animal2, animal3, animal4
('cat', 'dog', 'cat', 'procupine')