This lesson is being piloted (Beta version)

Variables and Assignment

Overview

Teaching: 40 min
Exercises: 20 min
Questions
  • 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:

This means that, for example:

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 as Sticky Notes

Variables must be created before they are used.

last_name
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-c1fbb4e96102> in <module>()
----> 1 last_name

NameError: name 'last_name' is not defined

Python is case-sensitive.

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.

first_name = Ahmed
age = 42
print(first_name, 'is', age, 'years old')
Ahmed is 42 years old

Variables persist between cells.

print(first_name, 'weighs', weight, 'kg')
Ahmed weighs 60 kg

Use meaningful variable names.

flabadab = 42
ewr_422_yY = 'Ahmed'
print(ewr_422_yY, 'is', flabadab, 'years old')

Choosing 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:

  1. ts = m * 60 + s
  2. tot_sec = min * 60 + sec
  3. total_seconds = minutes * 60 + seconds

Solution

minutes is better because min might mean something like “minimum” (and actually does in Python, but we haven’t seen that yet).

Variables can be used in calculations.

age = age + 3
print('Age in three years:', age)
Age in three years: 45

Variables only change value when something is assigned to them.

first = 1
second = 5 * first
first = 2
print('first is', first, 'and second is', second)
first is 2 and second is 5

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 and y using the swap 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 and age 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 print to display values.

  • 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.