Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 2: Values, variables, and expressions

Objectives: LO-2.1, LO-2.2, LO-2.3, LO-2.4
Prerequisites: Module 1
Time: about 5.5 hours: 2 for this reading, 2 for Lab 2, and 1.5 for the practice

Module 1’s programs worked everything out in one line and printed it. Real programs keep values and use them again, and they work with values the user types in. In this module you learn the four basic kinds of value Python has, three more arithmetic operators, variables, which give values names, and how to read input and turn it into numbers. You also learn to print numbers exactly as you want them, and why Python printed 7.199999999999999 in Lab 1.

Values and types

Every value in Python has a type, which says what kind of value it is and what you can do with it. The four types you meet first are:

TypePython’s nameExamplesWhat it holds
Integerint42, 0, -7Whole numbers, as large as memory allows
Floating-point numberfloat3.5, 2.0, -0.25Numbers with a decimal point
Stringstr"hello", '42', ""Text
BooleanboolTrue, FalseOne of two values: true or false

The function type tells you a value’s type:

print(type(42), type(3.5), type("hi"), type(True))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>

(class is Python’s word for a type; Module 14 explains it.) The type decides what an operation does. 2.0 and 2 are equal numbers of different types, and "42" is not a number at all, but a string of two characters. An expression is any piece of code that Python can work out to a value, such as 2 + 3, "hi", or type(42). To evaluate an expression is to work it out.

The two Boolean values are spelled True and False, with capital letters, and comparisons such as 5 > 3 produce them. Module 3 is about them.

More arithmetic: floor division, remainder, and power

Python has three more arithmetic operators:

OperatorNameExampleValue
//Floor division: divide, then round down to a whole number7 // 23
%Remainder, also called modulo: what is left over after floor division7 % 21
**Power2 ** 101024

// and % work as a pair. 7 // 2 asks “how many whole 2s fit in 7?” (3), and 7 % 2 asks “what is left over?” (1). They are the tools for splitting a quantity into units.

Worked example: minutes into hours

A film runs 135 minutes. How many hours and minutes is that?

print(135 // 60, "hours and", 135 % 60, "minutes")
2 hours and 15 minutes

135 // 60 is 2, because two whole hours fit in 135 minutes, and 135 % 60 is 15, the 15 minutes left over. The same pair turns seconds into minutes, centimeters into meters, or days into weeks.

Integers, floats, and rounding down

When both sides of +, -, *, //, %, or ** are integers, the result is an integer. When either side is a float, the result is a float: 3 + 4.0 is 7.0, and 7.0 // 2 is 3.0. / is the exception: it always gives a float, as Module 1 showed, because its answer often isn’t whole.

“Rounding down” means toward the lower number, which for negative numbers is away from zero: -7 // 2 is -4, not -3, because -4 is below -3.5. The remainder follows: -7 % 2 is 1, because -4 * 2 + 1 is -7.

Which operator goes first

Python evaluates operators in this order, from first to last. Operators on the same row run from left to right, except **, which runs from right to left.

OrderOperators
1( ) parentheses
2**
3- in front of a single number, as in -x
4*, /, //, %
5+, -

Two results surprise people. -2 ** 2 is -4, because ** comes before the minus sign: it means -(2 ** 2). And 2 ** 3 ** 2 is 512, because ** runs from right to left: it means 2 ** (3 ** 2), which is 2 ** 9. A minus sign just after ** belongs to the power, so 2 ** -1 is 0.5. When in doubt, add parentheses; they cost nothing and tell the reader what you meant.

Try it. In the interactive interpreter, work out how many weeks and days 100 days is, using // and %. You should get 14 weeks and 2 days.

Variables

A variable is a name that refers to a value. You make one with an assignment statement: a name, an equals sign, and an expression.

price = 2.40
count = 3
total = price * count
print(total)
7.199999999999999

Python runs an assignment from right to left: first it evaluates the expression on the right, then it makes the name on the left refer to the result. So total = price * count looks up price and count, multiplies them, and gives the result the name total.

The = in an assignment doesn’t mean “is equal to”, as it does in mathematics. It means “make this name refer to this value”. That’s why this line, which makes no sense as an equation, is correct and common:

count = count + 1

It evaluates count + 1 using the current value of count, then makes count refer to the result. Python has a shorter way to write it, count += 1, and the same for the other operators: -=, *=, /=, and so on.

Using a name before any assignment has given it a value is a NameError, the same error that a misspelled name gives: to Python, a name nobody assigned and a misspelled name are the same thing.

Naming variables

A name is made of letters, digits, and underscores (_), and can’t start with a digit. Names are case-sensitive, so total and Total are different variables. A few words, such as if, for, True, and None, are keywords that Python reserves for itself and won’t accept as names.

Python programmers write variable names in lowercase, with underscores between words, a style called snake case: total_minutes, not totalMinutes or TotalMinutes. Python’s style guide, PEP 8, recommends it. Choose names that say what the value means: minutes_per_hour makes a program easier to read than m or x.

Tracing a program

To trace a program is to work through it line by line, writing down each variable’s value after each line, the way Python would. A table keeps it tidy. Here is a program and its trace:

a = 4
b = a * 2
a = a + 1
c = a + b
b = c - b
After lineabc
14
248
358
45813
55513

Two lines need care. Line 3 changes a to 5, but b stays 8: b was worked out from a on line 2, and later changes to a don’t reach back to it. Line 5 uses the old value of b (8) on the right, and only then makes b refer to the result, 5.

Tracing is how you find out what a program really does, as opposed to what you meant it to do. It’s the main tool for finding bugs that produce no error message.

Names refer to values

A good picture of a variable is a name with an arrow to its value. After the program above:

a ──→ 5
b ──→ 5
c ──→ 13

An assignment moves a name’s arrow to a new value; it never changes the value itself, and it never moves any other name’s arrow. That’s why changing a on line 3 didn’t change b. The two 5s in the picture may even be the same value, with two arrows pointing to it; for numbers, that makes no difference. For lists, in Module 7, it makes a great deal of difference, and this picture is what explains it.

Python Tutor draws these pictures for you: paste in a short program, click Visualize Execution, and step through it one line at a time. Use it to check your traces.

Try it. Trace this program by hand, then check it in Python Tutor: x = 3, y = x, x = x * 10, y = y + x. What are x and y at the end?

Strings, a little more

+ joins two strings, and * repeats a string a whole number of times. len gives a string’s length in characters.

greeting = "Hello" + ", " + "world"
print(greeting)
print("ab" * 3)
print(len(greeting))
Hello, world
ababab
12

str turns a value into a string, which is one way to join a number to text: "Total: " + str(42) is "Total: 42".

Reading input, and converting it

The function input shows a prompt, waits for the user to type a line and press Enter, and gives back what they typed, as a string:

name = input("What's your name? ")
print("Hello,", name)

Run as a script in a terminal, it looks like this, where Ada is what the user typed:

What's your name? Ada
Hello, Ada

input always gives back a string, even when the user types digits. To calculate with what they typed, convert it with int (to an integer) or float (to a float):

celsius = float(input("Temperature in Celsius: "))
fahrenheit = celsius * 9 / 5 + 32
print(celsius, "Celsius is", fahrenheit, "Fahrenheit")
Temperature in Celsius: 21
21.0 Celsius is 69.8 Fahrenheit

Notebook cells can run input too: JupyterLab shows a box under the cell to type in. The labs avoid it, though, because their checks run every cell without anyone at the keyboard. They run scripts with typed input given to them instead.

What a missing conversion does

Forget the conversion, and one of two things happens. Sometimes Python stops with an error:

age = input("Age: ")
print("Next year:", age + 1)
Age: 30
Traceback (most recent call last):
  File "/home/you/py101/age.py", line 2, in <module>
    print("Next year:", age + 1)
                        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

age is the string "30", and + can’t join a string and a number. Sometimes, worse, there is no error at all:

first = input("First number: ")
second = input("Second number: ")
print("Sum:", first + second)
First number: 10
Second number: 5
Sum: 105

Both values are strings, so + joins them, "10" and "5", into "105". A program that gives a wrong answer without an error is harder to fix than one that stops, which is why it pays to test a program with inputs whose answers you know. Converting each input with float makes it print Sum: 15.0.

When conversion fails

int and float raise a ValueError when the string isn’t a number they can read:

int("3.5")
ValueError: invalid literal for int() with base 10: '3.5'

A literal here means the text of a number. “Base 10” means ordinary decimal digits. int reads only whole numbers, so "3.5" fails, though float("3.5") works. int and float ignore spaces around the digits, so int(" 7 ") is 7; but int("abc"), int(""), and int("3,5") all fail.

Given a float rather than a string, int cuts off everything after the decimal point: int(3.9) is 3, and int(-3.9) is -3. That’s not rounding; for rounding, use round, below.

Try it. Write a script that asks for a number of minutes and prints it in hours and minutes, using the worked example’s // and %. Run it in VS Code, and type 135.

f-strings: printing values in a format you choose

An f-string is a string with an f before its opening quote. Inside it, any expression in curly braces, {…}, is evaluated, and its value is put into the string:

name = "Ada"
count = 3
print(f"{name} bought {count} muffins for {count * 2.40}.")
Ada bought 3 muffins for 7.199999999999999.

After the expression, a colon starts a format specification, which says how to write the value. The ones you need most are:

SpecificationMeaningExampleResult
.2fTwo digits after the decimal pointf"{7.199999999999999:.2f}"7.20
,Commas between thousandsf"{1234567.891:,.2f}"1,234,567.89
.1%Multiply by 100, one decimal, and add a percent signf"{0.4567:.1%}"45.7%
<8At least 8 characters wide, lined up on the leftf"[{'tea':<8}]"[tea ]
>8.2f8 wide, lined up on the right, with two decimalsf"[{3.6:>8.2f}]"[ 3.60]

The square brackets in the last two examples are only there to show the spaces.

Worked example: a receipt that lines up

tea = 2 * 1.80
muffins = 3 * 2.40
print(f"{'Teas':<10}{tea:>8.2f}")
print(f"{'Muffins':<10}{muffins:>8.2f}")
print(f"{'Total':<10}{tea + muffins:>8.2f}")
Teas          3.60
Muffins       7.20
Total        10.80

Each label takes 10 characters, lined up on the left, and each amount takes 8, lined up on the right with two decimals, so the decimal points line up. Formatting changes only how a value is written: muffins is still 7.199999999999999.

Floats are approximate

Why did Python print 7.199999999999999 for 3 * 2.40? A computer stores a float in binary, in a fixed number of binary digits (bits). Most decimal fractions, such as 0.1 or 2.40, have no exact binary form, in the same way that 1/3 has no exact decimal form: 0.333… goes on forever, and any fixed number of digits cuts it short. So the float that Python stores for 2.40 is very slightly off, and the error shows up in the result.

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
0.30000000000000004
False

(== asks whether two values are equal, and gives True or False; Module 3 covers it.) The error is tiny, less than a millionth of a billionth of the value, but it is enough to make two floats that should be equal compare as different. Three habits follow:

  1. Format floats for people. Print them with an f-string such as :.2f.

  2. Don’t compare floats with ==. Ask whether they are close instead, with math.isclose:

    import math
    print(math.isclose(0.1 + 0.2, 0.3))
    True

    import math makes Python’s math module available: a module is a file of ready-made code, and math.isclose means the function isclose from the math module. Module 9 teaches modules properly.

  3. Count money in whole units. Programs that handle money often count in cents, as integers, which are exact. Python’s decimal module, outside this course’s scope, offers exact decimal arithmetic too.

Rounding

round(x, 2) rounds x to two decimal places, and round(x) rounds it to a whole number, giving an integer. When a number is exactly halfway, round goes to the even neighbor, a rule called “round half to even”: round(0.5) is 0, round(1.5) is 2, and round(2.5) is 2. The rule avoids pushing totals upward when many halves are rounded.

Floats make rounding surprising too. round(2.675, 2) is 2.67, not 2.68, because the float stored for 2.675 is slightly less than 2.675, so it isn’t halfway at all.

Common misconceptions

BeliefWhat Python doesExample that breaks it
= means “is equal to”It makes a name refer to a valuecount = count + 1 is correct, and changes count
Changing a variable changes the variables worked out from itEach assignment happens once, with the values of that momentAfter a = 4, b = a * 2, a = 5, b is still 8
input gives a number when the user types digitsIt always gives a stringinput() + input() with 10 and 5 typed gives "105"
int(3.9) rounds to 4It cuts off the fractionint(3.9) is 3, and int(-3.9) is -3
// rounds toward zeroIt rounds down-7 // 2 is -4
-2 ** 2 is 4** goes before the minus sign-2 ** 2 is -4; (-2) ** 2 is 4
Floats are exactMost decimal fractions are stored slightly off0.1 + 0.2 == 0.3 is False
round rounds halves upIt rounds halves to even, and floats may not be exactly halfround(2.5) is 2, and round(2.675, 2) is 2.67

Summary

Self-check

Answer each question before you open its answer.

  1. What are the type and value of 17 // 5, 17 % 5, 17 / 5, and 17.0 // 5?

    Answer

    3 (int), 2 (int), 3.4 (float), and 3.0 (float). // and % give integers when both sides are integers, / always gives a float, and one float operand makes // give a float.

  2. After x = 3, y = x, x = x * 10, and y = y + x, what are x and y?

    Answer

    x is 30 and y is 33. y = x makes y refer to 3. Changing x to 30 doesn’t change y. Then y + x is 3 + 30.

  3. A script runs n = input("How many? ") and then print(n * 2), and the user types 4. What does it print, and how do you make it print 8?

    Answer

    It prints 44: n is the string "4", and * repeats a string. Converting the input, n = int(input("How many? ")), makes it print 8.

  4. Write an f-string that prints the float price with exactly two decimal places, after the text Price: .

    Answer

    f"Price: {price:.2f}". For price = 3.5, it gives Price: 3.50.

  5. Why is 0.1 + 0.2 == 0.3 False, and what should a program do instead?

    Answer

    0.1, 0.2, and 0.3 have no exact binary form, so the stored floats are slightly off, and the sum comes out as 0.30000000000000004. Compare floats with math.isclose(0.1 + 0.2, 0.3), which is True.

Further reading