Variables and Assignment
Overview
Teaching: 40 min
Exercises: 20 minQuestions
How can I store data in programs?
Objectives
Write programs that assign scalar values to variables and perform calculations with those values.
Correctly trace value changes in programs that use scalar assignment.
Use variables to store values
You’ve seen how Python can be used as a calculator:
3 + 5 * 4
23
This is great but not very interesting.
To do anything useful with data, we need to assign its value to a variable.
In Python, we can assign a value to a
variable, using the equals sign =
.
For example, to assign the value 60
to a variable weight_kg
, we would execute:
weight_kg = 60
From now on, whenever we use weight_kg
, Python will substitute the value we assigned to
it. In essence, a variable is just a name for a value.
In Python, variable names:
- can include letters, digits, and underscores
- cannot start with a digit
- are case sensitive.
- underscores at the start like
__alistairs_real_age
have a special meaning so we won’t do that until we understand the convention.
This means that, for example:
weight0
is a valid variable name, whereas0weight
is notweight
andWeight
are different variables
Variables as Sticky Notes
A variable is analogous to a sticky note with a name written on it: assigning a value to a variable is like putting that sticky note on a particular value.
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.
last_name
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-c1fbb4e96102> in <module>()
----> 1 last_name
NameError: name 'last_name' is not defined
- The last line of an error message is usually the most informative.
- We will look at error messages in detail later.
Python is case-sensitive.
- Python thinks that upper- and lower-case letters are different,
so
Name
andname
are different variables. - There are conventions for using upper-case letters at the start of variable names so we will use lower-case letters for now.
weight
60
Weight
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-4ab70f7f1bf7> in <module>()
----> 1 Weight
NameError: name 'Weight' is not defined
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.
- The values passed to the function are called ‘arguments’
first_name = Ahmed
age = 42
print(first_name, 'is', age, 'years old')
Ahmed is 42 years old
print
automatically puts a single space between items to separate them.- And wraps around to a new line at the end.
Variables persist between cells.
- Variables defined in one cell exist in all other cells once executed, so the relative location of cells in the notebook do not matter (i.e., cells lower down can still affect those above).
- Notebook cells are just a way to organize a program; as far as Python is concerned, all of the source code is one long set of instructions.
print(first_name, 'weighs', weight, 'kg')
Ahmed weighs 60 kg
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')
- Use meaningful variable names to help other people understand what the program does.
- The most important “other person” is your future self.
Choosing a Name
Which is a better variable name,
m
,min
, orminutes
? 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
Solution
minutes
is better becausemin
might mean something like “minimum” (and actually does in Python, but we haven’t seen that yet).
Variables can be used in calculations.
- We can use variables in calculations just as if they were values.
- Remember, we assigned 42 to
age
a few lines ago.
- Remember, we assigned 42 to
age = age + 3
print('Age in three years:', age)
Age in three years: 45
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.
first = 1
second = 5 * first
first = 2
print('first is', first, 'and second is', second)
first is 2 and second is 5
- 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
Fill the table showing the values of the variables in this program after each statement is executed.
# Command # Value of x # Value of y # Value of swap # x = 1.0 # # # # y = 3.0 # # # # swap = x # # # # x = y # # # # y = swap # # # #
Solution
# Command # Value of x # Value of y # Value of swap # x = 1.0 # 1.0 # not defined # not defined # y = 3.0 # 1.0 # 3.0 # not defined # swap = x # 1.0 # 3.0 # 1.0 # x = y # 3.0 # 3.0 # 1.0 # y = swap # 3.0 # 1.0 # 1.0 #
These three lines exchange the values in
x
andy
using theswap
variable for temporary storage. This is a fairly common programming idiom.
Predicting Values
What is the final value of
position
in the program below? (Try to predict the value without running the program, then check your prediction.)initial = "left" position = initial initial = "right"
Check Your Understanding
What values do the variables
mass
andage
have after each statement in the following program? Test your answers by executing the commands.mass = 47.5 age = 122 mass = mass * 2.0 age = age - 20 print(mass, age)
Solution
95.0 102
Sorting Out References
What does the following program print out?
first, second = 'Grace', 'Hopper' third, fourth = second, first print(third, fourth)
Solution
Hopper Grace
Key Points
Use variables to store values.
Use
Variables persist between cells.
Variables must be created before they are used.
Python is case-sensitive.
Use meaningful variable names.
Variables can be used in calculations.