Variables and Assignment

Overview

Teaching: 10 min
Exercises: 10 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.

Use meaningful variable names.

flabadab = 42

Use comments to add documentation to programs.

Use print to display values.

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

Variables must be created before they are used.

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

Syntax errors are another common error seen.

# Forgetting an end quote causes a syntax error.
last_name = 'Feng
  File "<ipython-input-56-f42768451d55>", line 2
    name = 'Feng
                ^
SyntaxError: EOL while scanning string literal

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, create two cells with the following content, in this order:

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.

Variables can be used in calculations.

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

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

print(position)
left

The initial variable is assigned the value 'left'. In the second line, the position variable also receives the string value 'left'. In third line, the initial variable is given the value 'right', but the position variable retains its string value of 'left'.

Variables only change value when something is assigned to them.

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

Key Points

  • Use variables to store values.

  • Use print to display values.

  • Variables persist between cells.

  • Variables must be created before they are used.

  • Variables can be used in calculations.

  • Python is case-sensitive.

  • Use meaningful variable names.