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.

Lab 2: Values, variables, and expressions

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

In this lab you predict what expressions give before Python works them out, trace variables, write scripts that read what the user types, find the bug that a missing conversion causes, and print numbers the way people expect to read them. As in Lab 1, each exercise ends with a check cell that prints passed or says what is wrong, and fails until you answer.

Run the cells in order, from the top, with Shift+Enter.

Setup

Run the next cell first. It prints the version of Python, makes the scratch folder, and defines the two helpers from Lab 1, with one addition: both now take the text a user would type.

run_script("scratch/age.py", typed="30\n") runs the script as if a user typed 30 and pressed Enter (\n stands for pressing Enter). Every time the script calls input, it reads the next typed line. The helper shows the typed text after the prompt, as a terminal does, so the output looks the way it would if you ran the script yourself. If a script asks for more lines than typed holds, it stops with an EOFError (“end of file”), meaning it ran out of input.

1. Types and operators

type names the type of any value. Run the cell, then change the value inside type( ) to 7 // 2, then 7.0 // 2, then "7" * 2, and run it after each change.

// and % split a quantity into whole units and what is left over. Change minutes to 59, 60, 61, and 1,000 (typed as 1000, without the comma), and run the cell each time.

Exercise L2.1 (LO-2.1, ★, about 15 minutes)

Predict the value of each expression, without running it, and write your prediction the way Python would show the value: a whole number for an int (4), a number with a decimal point for a float (4.0), and text in quotes for a str ("4"). The type counts: 4 and 4.0 are different answers.

NameExpression
p19 / 3
p29 // 4
p39 % 4
p49.0 // 4
p52 + 3 * 4 ** 2
p6-3 ** 2
p7"3" + "4"
p8"ab" * 2 + "c"

Then run the check. It lists every prediction that differs from Python’s value; work out why before you change it.

Hint

/ always gives a float. ** runs before *, and before a minus sign in front of a number. + and * on strings join and repeat them.

2. Variables

Exercise L2.2 (LO-2.2, ★, about 10 minutes)

Trace this program on paper, in a table with a column for each variable and a row for each line, as the reading does. Then write the final value of each variable in the next cell.

a = 2
b = a + 3
a = b * 2
c = a - b
b = b + c

Once the check passes, paste the program into Python Tutor and step through it, comparing each step with your table.

The next cell tries to swap the values of two variables, so that left refers to "coffee" and right to "tea". Predict what it prints, then run it.

Both names end up referring to "coffee". The third line moved left’s arrow to "coffee", and after that nothing referred to "tea" any more, so the fourth line had nothing to copy.

Exercise L2.3 (LO-2.2, ★★, about 10 minutes)

Below the first two lines of the next cell, add lines that swap the values of left and right. Use a third variable, named temp, to keep one value safe while you move the other. Don’t type "tea" or "coffee" again: the swap must work whatever the two values are.

Hint

Think of swapping the drinks in two cups with a third, empty cup. Pour one drink into the empty cup first.

Python also has a one-line swap, left, right = right, left, which Module 7 explains.

3. Reading input

The next cell saves a script that reads a name and greets the user, and the cell after it runs the script with Ada typed in. Run both, then change typed to your own name and run it again.

Now run the same script in VS Code’s terminal, where you type the name yourself: .venv\Scripts\python scratch\greet.py on Windows, or .venv/bin/python scratch/greet.py on macOS and Linux.

Exercise L2.4 (LO-2.3, ★, about 15 minutes)

Write a script, scratch/hours.py, that asks for a number of minutes with the prompt Minutes: and prints it in hours and minutes. With 135 typed, it prints exactly:

Minutes: 135
135 minutes is 2 hours and 15 minutes

The first line is the prompt with the typed text, which the helper shows; your script prints only the second. The check also types 60, 59, and 0.

Hint 1

input gives a string. Convert it with int before you use // and %.

Hint 2

Give print five things: the minutes, the text "minutes is", the hours, the text "hours and", and so on. print puts the spaces between them.

Exercise L2.5 (LO-2.3, ★, about 10 minutes)

This script stops with an error when the user types 30. Run it and read the message. Then fix the script so that it prints Next year you will be 31, and fill in the kind of error the original script had.

Exercise L2.6 (LO-2.3, ★★, about 15 minutes)

This script adds two prices. Run it: it prints a total without any error, but the total is wrong. Work out why, then fix the script so that it prints Total: 3.75 for these prices.

Hint

What does + do with two strings? Prices can have a decimal point, so which conversion do they need?

This bug is more dangerous than the one in Exercise L2.5, because nothing tells you it is there. Only running the program with inputs whose answer you already know shows it.

4. Formatting with f-strings

Run the next cell, then change the format specification after the colon to .1f, .3f, ,.2f, >12.2f, and .0%, and run it after each change. The square brackets show where the spaces go.

Exercise L2.7 (LO-2.4, ★★, about 15 minutes)

A shop sells pens at 1.15 each, notebooks at 3.40 each, and erasers at 0.65 each. Write a script, scratch/shop.py, that prints a receipt for 4 pens, 2 notebooks, and 1 eraser, exactly like this:

Pens            4.60
Notebooks       6.80
Eraser          0.65
Total          12.05

Each label is 12 characters wide, lined up on the left, and each amount 8 characters wide, lined up on the right, with two decimals. Let Python work out every amount, and use f-strings for the layout, not spaces you type yourself.

Hint 1

The reading’s worked example “a receipt that lines up” does the same with widths 10 and 8.

Hint 2

Store each amount in a variable first, such as pens = 4 * 1.15. Then the total is the sum of three variables, and each print holds one f-string.

The format only changes how a number is shown. Print the unformatted total in the next cell, and see why the receipt needed .2f.

5. Floats are approximate

Run the next cell. Then change 0.6 to 0.6000000000000001 and run it again.

Exercise L2.8 (LO-2.4, ★★, about 15 minutes)

  1. Set equal to an expression that compares total with 0.6 the right way for floats, so that it is True.

  2. Predict the values of round(0.5), round(1.5), round(2.5), and round(3.5), without running them, and write them as r1 to r4.

  3. Predict round(2.675, 2), and write it as r5.

Hint

The reading’s section “Rounding” gives the rule for halves, and why 2.675 isn’t really a half.

The messages in that check give the answers away once you run it, so make your predictions first: a wrong prediction you then understand teaches you more than a right one you copied.

6. Putting it together

Exercise L2.9 (LO-2.3, LO-2.4, ★★, about 20 minutes)

Write a script, scratch/convert.py, that asks for a temperature in Celsius with the prompt Celsius: , converts it to Fahrenheit with F=C×9/5+32F = C \times 9/5 + 32, and prints both with one decimal. With 21 typed, it prints:

Celsius: 21
21.0 C = 69.8 F

Temperatures can have decimals, such as 37.5. Write the whole script yourself; the check types 21, -40, 37.5, and 100.

Summary

In this lab you:

  • predicted the type and value of expressions with /, //, %, **, and strings;

  • traced variables, and swapped two of them with a third;

  • wrote scripts that read input, converted it with int and float, and found the error and the silent wrong answer that a missing conversion causes;

  • lined up a receipt with f-strings and format specifications; and

  • compared floats with math.isclose, and saw how round treats halves.

Next, the Module 2 practice gives you more exercises with answers, and Module 3 shows how a program makes decisions with the True and False you met here.