Overview
Teaching: 10 min
Exercises: 0 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.
=
symbol assigns the value on the right to the name on the left.age
and a name in quotation marks to a variable first_name
.age = 42
eye_color = 'green'
first_name = 'Ahmed'
_
(typically used to separate words in long variable names)__alistairs_real_age
have a special meaning
so we won’t do that until we understand the convention.print
to display values.print
that prints things as text.print(first_name)
Ahmed
Python’s print
function can also display multiple items at once.
print(first_name, 'is', age, 'years old')
print first_name, 'has', eye_color, 'eyes'
('Ahmed', 'is', 42, 'years old')
Ahmed has green eyes
Note in the first case without parenthesis we get a different output format than
in the second case. This is just a difference in the way that our version of
iPython prints information. Both are OK, but the first version (with
parenthesis) will work on any version of Python, so we’ll continue to teach that
throughout the workshop today. Also note that each print
command starts a new
line in the output displayed.
Extra information on the print command in Python
In Python 2.7 (which is what we’re using today),
print(last_name)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-c1fbb4e96102> in <module>()
----> 1 print(last_name)
NameError: name 'last_name' is not defined
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). Remember: 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.
age
a few lines ago.age = age + 3
print('Age in three years:', age)
Age in three years: 45
atom_name = 'helium'
print(atom_name[0])
h
[start:stop]
, where start
is replaced with the
index of the first element we want and stop
is replaced with the index of
the element just after the last element we want.[start:stop)
.atom_name = 'sodium'
print(atom_name[0:3])
sod
len
to find the length of a string.print(len('helium'))
6
Name
and name
are different variables.flabadab = 42
ewr_422_yY = 'Ahmed'
print(ewr_422_yY, 'is', flabadab, 'years old')
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"
Solution
'left'
The
initial
variable is assigned the value “left”. In the second line, theposition
variable also receives the string value “left”. In third line, theinitial
variable is given the value “right”, but theposition
variable retains its string value of “left”.
Challenge
If you assign
a = 123
, what happens if you try to get the second digit ofa
viaa[1]
?Solution
Numbers are not stored in the written representation, so they can’t be treated like strings.
a = 123 print(a[1])
TypeError: 'int' object is not subscriptable
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).
Slicing
What does the following program print?
atom_name = 'carbon' print('atom_name[1:3] is:', atom_name[1:3])
atom_name[1:3] is: ar
- What does
thing[low:high]
do?- What does
thing[low:]
(without a value after the colon) do?- What does
thing[:high]
(without a value before the colon) do?- What does
thing[:]
(just a colon) do?- What does
thing[number:negative-number]
do?
Key Points
Use variables to store values.
Use
Variables persist between cells.
Variables must be created before they are used.
Variables can be used in calculations.
Use an index to get a single character from a string.
Use a slice to get a substring.
Use the built-in function
len
to find the length of a string.Python is case-sensitive.
Use meaningful variable names.