Variables and Assignment#
Questions#
How can I store data in programs?
Learning Objectives#
Write programs that assign values to variables and perform calculations with those values.
Correctly trace value changes in programs that use scalar assignment.
Use variables to store values.#
Variables are names for values.
In Python the
=
symbol assigns the value on the right to the name on the left.The variable is created when a value is assigned to it.
Here, Python assigns an age to a variable
age
and a name in quotes to a variablefirst_name
.
age = 42
first_name = 'Ahmed'
Variable names
can only contain letters, digits, and underscore
_
(typically used to separate words in long variable names)cannot start with a digit
are case sensitive (age, Age and AGE are three different variables)
Variable names that start with underscores like
_python_is_awesome
have a special meaning so we won’t do that until we understand the convention.
Use print
to display values.#
Python has a built-in function called
print
that prints things as text.Call the function (i.e., tell Python to run it) by using its name.
Provide values to the function (i.e., the things to print) in parentheses.
To add a string (a sequence of characters - e.g., your name) to the printout, wrap the string in single or double quotes.
Python doesn’t care if you use single
' '
or double" "
quotes, as long as you are consistent within your expression.
The values passed to the function are called arguments
print(first_name, 'is', age, 'years old')
Ahmed is 42 years old
print
automatically puts a single space between items to separate them.It also wraps around to a new line at the end.
f-strings in Python#
There is an even more convenient way to print strings than shown above.
Python has recently introduced formatted string literals.
Simply include an
f
before the quotes in anyprint
statement.Now, add curly braces containing expressions (e.g.,
{my_variable}
; those expressions will then be replaced by their values when printed to the screen.Removes the need for extraneous quotation marks and commas.
print(f"{first_name} is {age} years old")
Ahmed is 42 years old
Use input
to assign a value to a variable through user input.#
Python has a built-in function called
input
that accepts user input and assigns it to a variable.Call the function (i.e., tell Python to run it) by using its name.
You can request a specfiic user input by wrapping your probe in quotes.
By default,
input
interprets the user’s input as a string, even if numbers are entered.
first_name = input("What is your first name?")
age = input("How old are you?")
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[4], line 1
----> 1 first_name = input("What is your first name?")
2 age = input("How old are you?")
File ~/opt/anaconda3/envs/jupyter_books/lib/python3.10/site-packages/ipykernel/kernelbase.py:1172, in Kernel.raw_input(self, prompt)
1165 """Forward raw_input to frontends
1166
1167 Raises
1168 ------
1169 StdinNotImplementedError if active frontend doesn't support stdin.
1170 """
1171 if not self._allow_stdin:
-> 1172 raise StdinNotImplementedError(
1173 "raw_input was called, but this frontend does not support input requests."
1174 )
1175 return self._input_request(
1176 str(prompt),
1177 self._parent_ident["shell"],
1178 self.get_parent("shell"),
1179 password=False,
1180 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
print(first_name, 'is', age, 'years old')
print(f"{first_name} is {age} years old.")
Variables must be created before they are used.#
If a variable doesn’t exist yet, or if the name has been mis-spelled, Python reports an error. (Unlike some languages, which “guess” a default value.)
print(last_name)
The last line of an error message is usually the most informative.
We will look at error messages in detail later.
Variables persist between cells#
Be aware that it is the order of execution of cells that is important in a Jupyter notebook, not the order in which they appear. Python will remember all the code that was run previously, including any variables you have defined, irrespective of the order in the notebook. Therefore if you define variables lower down the notebook and then (re)run cells further up, those defined further down will still be present. As an example, consider the following
print(myval)
myval = 1
If you execute this in order, the first cell will give an error. However, if you run the first cell after the second cell it will print out 1
. It’s possible to drag ‘n drop cells in CoCalc, to reorder them.
myval = 1
print(myval)
If you start to get confused about what order you’ve run cells in, it can be helpful to use the Kernel
-Restart & Run All
menu option which clears the interpreter and runs everything from a clean slate going top to bottom.
Variables can be used in calculations.#
We can use variables in calculations just as if they were values.
Remember, we assigned the value
42
toage
a few lines ago.
Before running the next cell, what do you think will be printed to the screen?
age = age + 3
print('Age in three years:', int(age))
Python is case-sensitive.#
Python thinks that upper- and lower-case letters are different, so
Name
andname
are different variables. You can prove this by runningprint(Age)
in the cell below.There are conventions for using upper-case letters at the start of variable names— they should only be used in specific circumstances in Python — so it is good practice to only use lower-case letters for variable names
print(Age)
Use meaningful variable names.#
Python doesn’t care what you call variables as long as they obey the rules (alphanumeric characters and the underscore).
flabadab = 42
ewr_422_yY = 'Ahmed'
print(ewr_422_yY, 'is', flabadab, 'years old')
However, if you use meaningful variable names, you help other people (and your future self!) understand what the program does
A word about expressions and the order of operations#
An expression is a piece of code that represents a value. If we are dealing with numerical expressions, the algebraic precedence rules from arithmetic apply. A simple mnemonic for those rules is “PEDMAS”, which stands for:
(P)arentheses, then
(E)xponents, then
(D)ivision or (M)ultiplication (both have equal precedence, and so the order is determined left to right), then
(A)ddition or (S)ubtraction (both have equal precedence, and so the order is determined left to right)
So, for example:
2 + 5 * 7
is equivalent to:
2 + 35
not
7 * 7
BUT
(2 + 5) * 7
evaluates to:
7 * 7
Exponents are indicated by the exponent (**) operator:
2**3
is equivalent to 2^3 and thus equals 8.
Translating equations into Python#
Another thing to keep in mind when writing mathematical expressions is that, while you will see many equations in textbooks, websites, papers, etc. that use square brackets, like in this equation: \(y = \left[\frac{x}{(1-z)}\right] + \left[\frac{x^2}{\frac{1}{x^2}+z}\right]\)
In Python, round parentheses [brackets] (i.e., ( )
) are used for equations. Square brackets are used for lists and indexing (locating an item or items in a data container). So, the above equation, could be written as follows in Python:
y = (x / (1 - z)) + (x**2 / (1 / x**2 + z))
Basic Python data types#
So far we have seen two basic Python data types: Integer and String. There is another basic data type, Boolean. Boolean variables can only have the values of either True
or False
. (Remember, Python is case-sensitive, so be careful of your spelling.) We can define variables to be of type boolean by setting their value accordingly. Boolean variables are a good way of coding anything that has a binary range (eg: yes/no), because it’s a type that computers know how to work with as we will see soon.
print(True)
print(False)
bool_val_t = True
print(type(bool_val_t))
print(bool_val_t)
bool_val_f = False
print(type(bool_val_f))
print(bool_val_f)
True
False
<class 'bool'>
True
<class 'bool'>
False
The following two lines of code will generate an error because Python is case-sensitive. We need to use ‘True’ instead of ‘true’ and ‘False’ instead of ‘false’.
print(true)
print(false)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In [2], line 1
----> 1 print(true)
2 print(false)
NameError: name 'true' is not defined
We can also get values of Boolean type using comparison operators, basic ones in Python are ==
for “equal to”, !=
for “not equal to”, and >
, <
, or >=
, <=
.
print('hello' == 'HELLO')
print(3 != 77)
print(1 < 2)
print('four' > 'three')
False
True
True
False
Style note:
Although Python allows you to use virtually any characters in variable names, there are style conventions that you should learn and follow. Python PEP 8](https://www.python.org/dev/peps/pep-0008/#naming-conventions) (PEPs are the “Python Enhancement Proposals” that provide standards for the language) specifies that regular variables “should be lowercase, with words separated by underscores as necessary to improve readability”.
So, you should only use lower-case letters in variable names. This is because upper-case letters are used for specific purposes in Python. As well, if your variable name is more than one word (such as first_name
), you should use underscores to separate the words. This naming convention is called snake case.
You may encounter different conventions as standard in other programming languages (or in examples of Python that don’t properly follow style conventions), such as camel case which would be FirstName
or possibly firstName
(for the aficionados: the first is is a sub-type of camel case called Pascal case, while the second is dromedary case).
There is a good reason for following these conventions: when a seasoned Python programmer sees something in camel case, they will expect it to be a class or type variable, not a regular variable. Following Python’s conventions thus improves the readability, sharability, and transparency of code. Lastly, another advantage to following coding style conventions is that less time and energy needs to be spent on decision-making related to lower-level implementational details, freeing your mind up to focus more on what you want to accomplish with your code.
Exercises#
What’s in a name?#
Which is a better variable name, m
, min
, or minutes
? Why? (Hint: think about which code you would rather inherit from someone who is leaving the lab):
ts = m * 60 + s
tot_sec = min * 60 + sec
total_seconds = minutes * 60 + seconds
Variables only change value when something is assigned to them#
If we make one cell in a spreadsheet depend on another, and update the latter, the former updates automatically
This does not happen in programming languages
Before executing the next cell, what do you think will get printed to the screen? Why?
first = 1
second = 5 * first
first = 2
print('first is', first, 'and second is', second)
The computer reads the value of
first
when doing the multiplication, creates a new value, and assigns it tosecond
.After that,
second
does not remember where it came from.
Swapping Values#
Try to follow what happens in the following sequence of commands. Guess what the final values of x
and y
will be, then run the code yourself to check your guess.
x = 1.0
y = 3.0
swap = x
x = y
y = swap
These three lines exchange the values in x
and y
using the swap
variable for temporary storage. This is a fairly common programming idiom.
Key Points Summary:#
Use variables to store values
Use
print
to display valuesVariables persist between cells
Variables must be created before they are used
Variables can be used in calculations
Python is case-sensitive
Variables only change value when something is assigned to them
Use meaningful variable names
Use only lower-case letters, separated by underscores, in variable names
This section was adapted from the Software Carpentry Plotting and Programming in Python workshop, Aaron J. Newman’s Data Science for Psychology and Neuroscience - in Python and Meghan Allen’s CPSC 103 course at UBC, which contributed to the section on evaluating expressions.