Variables

Arithmetic operators allow Python to act like a calculator. Most calculators remember the value of the previous result so that further operations can be executed without starting over. In programming, the value of any previous computation can be stored for later use by creating a variable.

Assigning Variables

The = operator creates a variable by assigning a name to a value. The process goes from right to left: the values on the right side of = are evaluated, then associated with the name on the left side. In Google Colab, after executing a cell that defines a variable, that variable is available in all cells executed later in the same runtime.

# Assign the name x to the value 10.
x = 10
print(x)

# Now x can be used in arithmetic operations.
print(3 * x)
print(x**2)
10
30
100

Existing variables can be reassigned to new values by using = again.

# x, assigned in a previous cell, is currently assigned to the value 10.
print(x)

# Reassign x to a new value.
x = 20
print(x)
print(3 * x)
print(x**2)
10
20
60
400

How Memory Works

Computer memory is a bit like a display case. When Python creates a value, that value is stored somewhere in memory as an object. A variable is like a label attached to one of those objects: it allows the program to retrieve the value by looking into the display case at the right location.

In the statement x = 10, Python evaluates the right side of the assignment and gets the int object 10, then binds the name x to that object. Any time x is used later, Python looks up the name x and uses the object it is currently attached to. By executing x = 20, the name x is bound to a different object instead.

Objects that no longer have anything referring to them become eligible to be deleted by Python’s automatic garbage collector, thus freeing up space for other objects.

Variables in computer programming are similar to variables in mathematics: the preceding blocks evaluate \(3x\) and \(x^2\) for different values of the mathematical variable \(x\). However, variables in computer programming are often given English names that describe what they represent. Unless the program is highly mathematical, this makes a program much more readable. Consider the difference between the following blocks, which do the same computations but use different variable names.

dw = 7
wy = 52
dy = 365

ld = dy - (dw * wy)
print(ld)
1
days_per_week = 7
weeks_per_year = 52
days_per_year = 365

leftover_days = days_per_year - (days_per_week * weeks_per_year)
print(leftover_days)
1

Python variables can also be assigned to non-numerical values such as strings.

Augmented Assignment Operators

Python has a few extra operators for updating an existing variable with one arithmetic operation.

Operator

Usage

Equivalent to

+=

x += y

x = x + y

-=

x -= y

x = x - y

*=

x *= y

x = x * y

/=

x /= y

x = x / y

//=

x //= y

x = x // y

%=

x %= y

x = x % y

**=

x **= y

x = x**y

These operators are convenient, but be careful to place the = after the arithmetic operator:

  • x -= y is the same as x = x - y.

  • x =- y is the same as x = -y.

Problem 1

Suppose the local creamery has the following menu items.

  • Box of French fries, $2.49

  • Guacamole bacon burger, $8.69

  • Single scoop of ice cream, $3.99

There is a 7.45% sales tax on all purchases, and you happen to have a $5.00 coupon. The following code creates variables for each of these quantities.

# Menu item prices.
fries = 2.49
guac_burger = 8.69
ice_cream = 3.99

# Taxes and coupon value.
tax_rate = 0.0745  # 7.45%
coupon = 5.00

For an order of 3 fries, 2 burgers, and 2 ice creams, use the variables defined above to calculate and store the following quantities.

  1. Subtotal: the total cost of the order before tax or discounts.
    Store this value in a variable problem1_subtotal.

  2. Tax: the subtotal (use problem1_subtotal) multiplied by the tax rate.
    Store this value in a variable problem1_tax.

  3. Total: the subtotal plus the tax (use problem1_tax) minus the value of the coupon.
    Store this value in a variable problem1_total.

Test Cases

Solutions to most exercises in this class can be verified with appropriate tests. For this problem, you could calculate each quantity by hand and compare your results. As an additional spot check, if only 2 of each item were ordered, then the variables would have the following values.

print(problem1_subtotal)
print(problem1_tax)
print(problem1_total)
30.34
2.2603299999999997
27.60033

After running this check, remember to change the code back to the original order of 3 fries.

Don’t Overwrite Answers

Do not redefine the variables problem1_subtotal, problem1_tax, or problem1_total later in your notebook. The autograder only reads the final value of the variable at the end of the notebook.

Reserved Keywords

Variable names in Python must start with a letter (a-z, A-Z) or an underscore (_), and all other characters must be letters, underscores, or numbers (0-9). There are also a few reserved keywords that have special meanings and therefore cannot be used as variables.

help("keywords")
Here is a list of the Python keywords.  Enter any keyword to get more help.

False               class               from                or
None                continue            global              pass
True                def                 if                  raise
and                 del                 import              return
as                  elif                in                  try
assert              else                is                  while
async               except              lambda              with
await               finally             nonlocal            yield
break               for                 not                 
# Try to use a reserved word as a variable name.
True = "worldly philosophy"
  Cell In[6], line 2
    True = "worldly philosophy"
    ^
SyntaxError: cannot assign to True

Quick Check

Which of the following are valid Python variable names?

tk421
m@th
1nation
__underscored__
class
Answer

tk421 and __underscored__ are valid.

  • m@th is invalid because of the @.

  • 1nation is invalid because it starts with a number.

  • class is a reserved keyword.

Swapping Variables

Sometimes a program needs to exchange the values assigned to two variables. One naïve approach is to assign each variable to the other in turn.

# Define variables x and y.
x = 10
y = 20
print("Before swap")
print(x)
print(y)

# Try to exchange x and y.
x = y
y = x
print("After swap")
print(x)
print(y)
Before swap
10
20
After swap
20
20

The swap failed! To understand why, examine the code one line at a time.

  • First, x is assigned to 10 and y is assigned to 20.

  • x = y reassigns the name x to the current value of y, which is 20.

  • y = x reassigns the name y to the current value of x, which is now 20.

The original value of x is no longer available through either x or y. One way to do this properly is to create a third variable to temporarily track the first value.

# Define variables x and y.
x = 10
y = 20
print("Before swap")
print(x)
print(y)

# Exchange x and y.
temp = x    # Record the original value of x.
x = y       # Assign x to the value of y.
y = temp    # Assign y to the original value of x.
print("After swap")
print(x)
print(y)
Before swap
10
20
After swap
20
10

Because this is such a common task that is so easy to get wrong, Python implements a syntactic shortcut for swapping variables: x, y = y, x.

x = 10
y = 20
print("Before swap")
print(x)
print(y)

# Exchange x and y.
x, y = y, x
print("After swap")
print(x)
print(y)
Before swap
10
20
After swap
20
10