Variables and Assignment

Overview

Teaching: 10 min
Exercises: 5 min
Questions
  • How can I store data in programs?

Objectives
  • Write programs that assign values to variables and perform calculations with those values.

  • Correctly trace value changes in programs that use assignment.

Use variables to store values.

age = 42
first_name = 'Ahmed'

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

Variables can be used in calculations.

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

Use an index to get a single character from a string.

atom_name = 'helium'
print(atom_name[0])
h

Use a slice to get a substring.

atom_name = 'sodium'
print(atom_name[0:3])
sod

Python is case-sensitive.

Use meaningful variable names.

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

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"

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

Slicing

What does the following program print?

library_name = 'social sciences'
print('library_name[1:3] is:', library_name[1:3])
library_name[1:3] is: oc
  1. What does thing[low:high] do?
  2. What does thing[low:] (without a value after the colon) do?
  3. What does thing[:high] (without a value before the colon) do?
  4. What does thing[:] (just a colon) do?
  5. What does thing[number:negative-number] do?

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.

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