Quarry School

Programming in Python: crash course

about 37 min to listen6 units30 lessons0 questions to try

Short view. Each lesson's rule, its steps and its trap. Switch to Full for a worked example and a question to try in every lesson.Full view. Each lesson's rule, its steps, one worked example with Watch it solved, the trap, and one question to try.

Every unit, and under it every lesson. A unit's own crash course adds the unit's quick checks.

1 First programs

about 6 min5 lessonsOpen the unit's crash course

1.1 Run your first Python program

about 2 minOpen the full lesson

The rule

Lines you want to keep go in the editor window.

A line you want to try once goes after >>> in the Shell. Save the file, choose Run and then Run Module, and read the result in the Shell below the newest RESTART line. For print("Lantern") the printed line is Lantern. The quote marks belong to your instruction, and the >>> belongs to the Shell, so neither is part of the printed line.

How

  1. Open IDLE from your Python 3.13 installation. IDLE is an optional part of Python. If it is missing, look for instructions from whoever provided your Python. Depending on its settings and how you start it, IDLE may open an editor window when it starts. If you do not see the Shell, choose Run, then Python Shell, to open it.
  2. In the Shell, after the >>> prompt, type print("Lantern") and press Return. The Shell shows Lantern.
  3. Choose File, then New File, to open an empty editor window.
  4. In the editor window, type print("Lantern") on line 1. Type the instruction only, without >>>.
  5. Choose File, then Save. A new file has no name yet, so IDLE asks you for one with Save As. Type lantern.py. While a window has unsaved changes, its title has a * at each end. The title bar also shows the Python version, so check that it says 3.13.
  6. Choose Run, then Run Module. The IDLE documentation names F5 as the key for it. If you forgot to save, IDLE either asks you to save or saves for you, depending on its settings.
  7. Look at the Shell. You see a line containing RESTART, then Lantern, then the prompt.
  8. In the editor, change Lantern to Cove so the line reads print("Cove"). Save, then run again. Cove appears below a newer RESTART line. Lantern stays higher up, because the Shell keeps earlier output.

Worked example

Run the saved file

Python code
print("Lantern")

Standard input

Empty

Standard output

Lantern

Save the line in lantern.py. Choose Run Module in the editor, then look in the Shell for the printed line.

Edit and run again

Python code
print("Cove")

Standard input

Empty

Standard output

Cove

Change the text in the editor, save and run the file again. The Shell shows Cove on its own line.

The trap

The usual mistake is writing the expected output as >>> Lantern, or as Lantern inside quote marks. The >>> is the Shell's prompt. The Shell shows it after the run to say it is ready for your next line, so it is not part of what your program printed. The quote marks belong to your instruction, and the printed line is Lantern alone. A related slip is copying >>> into the editor window. The file holds only your instruction. If nothing new appears, check two things. Look in the Shell, because the result never appears in the editor. Then look at the window title, because a * at each end means your latest change is not saved yet.

1.2 Tell text from numbers

about 1 minOpen the full lesson

The rule

Use addition for two integers and joining for two strings.

Check for quote marks before deciding which operation this example uses.

How

  1. Find the + and the value on each side of it. In this lesson both values always have the same type.
  2. Look at the edges of each value for a pair of matching quote marks.
  3. If both values have quotes, they are strings: write the characters of the left value, then the characters of the right value.
  4. If neither value has quotes, they are integers: add them as you would on paper.
  5. Write what print shows: the result with no quote marks, on a line of its own.

Worked example

Predict both lines

Python code
print(7 + 2)
print("7" + "2")

Standard input

Empty

Standard output

9
72

On paper, count seven objects and two more. Then put a tile marked 7 next to one marked 2. The total is 9 and the two tiles read 72.

The trap

A natural mistake is to assume that anything made of digits will add. You see a 7 and a 2 in both 7 + 2 and "7" + "2", so it feels natural to expect 9 from both. The quote marks change the type: inside them each digit is a character tile, and + sets the tiles side by side to make 72. Before you predict a +, look at the edges of each value, not at the digits.

1.3 Give a value a name

about 2 minOpen the full lesson

The rule

An assignment has a name to the left of = and a value or calculation to the right.

Python works out the whole right-hand side first, then ties the left-hand name to the result. If that name already had a value, it now names the new one instead. No other name changes.

How

  1. Draw a state table with a column for the line, a column for what the right-hand side works out to, one column for each name and a column for output.
  2. Take the next line of the program. If it is an assignment, cover the left side with your finger and work out the right side, using the values in the row above.
  3. Write that result in the column of the name on the left. Carry every other name's value down unchanged from the row above.
  4. If the line is a print, write what it displays in the output column: the values in the order given, with one space between them.
  5. Repeat until the last line. The output column is your prediction. Compare it with the real output if you have Python 3.13, or with the printed answer if you are working on paper.

Worked example

Trace boxes and spare

Python code
boxes = 4
spare = boxes
boxes = boxes + 1
print(spare, boxes)

Standard input

Empty

Standard output

4 5

Follow the rows below. For a check in the Shell, enter the three assignments and then enter each name on its own.

The trap

The usual mistake is to predict 5 5. It comes from reading spare = boxes as a lasting link, as if spare will always match boxes. That line ran once, at step 2, and tied spare to 4. Step 3 moved only the boxes tag, because boxes was the only name on the left.

A second mistake is reading = as the equals sign from arithmetic. Read that way, boxes = boxes + 1 looks like nonsense, since no number equals itself plus one. In Python, = means "tie this name to this value". The comparison "is equal to" is written with two signs, ==, and a later unit teaches it.

Avoid saying that spare = boxes "makes a copy". The Python tutorial states that a simple assignment never copies data. It puts a second name on the value that is already there. This lesson keeps to whole numbers on purpose.

1.4 Read a reply from the keyboard

about 1 minOpen the full lesson

The rule

Keep the reply as text for a badge code, where every character matters.

For a count written in digits, convert the reply with int(reply) before adding to it.

How

  1. Type the Python source, the lines of code shown below, in your editor. Keep the blank line after reply = input() and save the file.
  2. Run the saved file with Python 3.13. The input() call has empty parentheses, so it waits for your reply without displaying a message asking for it. Type the two digits 04 where the program is running and press Enter.
  3. Compare the two lines the program prints with the expected output. The Shell can show your typed reply above those lines. If you’re working on paper, follow the code one line at a time and write down what each print() displays.

Worked example

One reply for a badge and a count

Python code
reply = input()

print(reply)
print(int(reply) + 1)

Prompt

Type 04 in the Shell and press Enter.

Standard input

04

Standard output

04
5

The first line of output keeps the two badge characters. To check the second line on paper, draw four strokes and add one.

The trap

A reply can look like a number and still be text. Writing reply + 1 skips the conversion. Use int(reply) + 1 for the count. For this version, enter a whole number written in digits, such as 04 or 8. The word four is outside the form that int() can convert here.

1.5 Use an error message to fix a program

about 1 minOpen the full lesson

The rule

Start at the reported line or the spot IDLE marks.

The mark gives you an approximate place to look. The fix may be nearby. For the misspelled name, compare the name inside the parentheses with the one beside =. For the unclosed call, look for the missing ). Make one change and run the file again so you can see what that change did.

How

  1. In IDLE for Python 3.13, use File, then New File to open an Editor window, where you type and save source. Save the file under the example’s name. In the Editor’s Run menu, choose Run Module. Read the program’s output in the Shell window. For these examples, type the source in the Editor and leave the Shell for reading.
  2. For the misspelled name, find the file name and line number in the Shell report. Open that file in the Editor if needed. Go to the indicated line, counting from 1 and including blank lines. Read the error class on the report’s last line. For the unclosed call, look for the spot IDLE marks in the Editor during the syntax check.
  3. Make one change in the Editor and save the file.
  4. Choose Run Module again and compare what appears in the Shell with your predicted output.

Worked example

Find the missing letter

Python code
seats = 3
print(seat)

Standard input

Empty

Standard output

Empty

Exception NameError

Read the error class on the last line and use the file and line number to find the misspelled name.

Run the repaired file

Python code
seats = 3
print(seats)

Standard input

Empty

Standard output

3

Write seats next to 3 on paper. The second line looks up that name and prints the value.

Read a syntax error

Python code
print("Gate open")

print("Gate closed"

Standard input

Empty

Standard output

Empty

Exception SyntaxError

The file has an unclosed call. Python reports a syntax error during parsing, before either line prints.

Close the parentheses

Python code
print("Gate open")

print("Gate closed")

Standard input

Empty

Standard output

Gate open
Gate closed

Save the corrected file. Read the two lines in order to predict its output.

The trap

Check the whole name when the error says NameError. If a call has an open parenthesis, find its closing partner before running the file. An unclosed call can stop the whole file during parsing.

2 Quantities and text

about 5 min5 lessonsOpen the unit's crash course

2.1 Choose an arithmetic operator

about 1 minOpen the full lesson

The rule

Use + to add an amount, - to take an amount away, * to find the total of equal groups and / to share an amount equally.

In 4 * 6, the operands are 4 and 6, the numbers that * works on.

Start with whole numbers such as 4 and 20. To subtract, put the starting amount first and the amount you remove second. To divide, put the amount to share first and the number of shares second. The number to the right of / is the divisor. In this example, it counts the frames, so it must be at least one.

Python calls numbers such as 2.5 and 5.0 floats. In these examples, / gives a float even when the share is a whole number of meters.

How

  1. Say what is happening. Are you adding a piece, taking one away, finding the total of equal groups or sharing equally?
  2. Choose the operator for that action. Put it between the two numbers in the order described above.
  3. To show the result, type print and put the calculation inside the parentheses ( and ). Type the source lines below in a file in your editor. Save it as ribbon.py and run it with Python 3.13. You can also follow along on paper with the printed trace, which shows the results in order.

Worked example

Ribbon for four display frames

Python code
print(4 * 6)
print(24 + 5)
print(29 - 9)
print(20 / 4)

Standard input

Empty

Standard output

24
29
20
5.0

Save the code as ribbon.py and run the file in Python 3.13. The first three lines show whole meter counts. The last line shows the share as a float. Four shares of 5 m give the 20 m you divided.

The trap

If you reach for the letter x when you mean “times,” type the asterisk *. That is Python’s multiplication sign.

Both numbers in 20 / 4 are whole numbers. The length per frame is exactly 5 m, and Python displays that result as 5.0. The .0 is part of how Python writes this float.

2.2 Group a calculation

about 1 minOpen the full lesson

The rule

When parentheses group an addition, do the addition inside them before multiplying by the number outside.

In a calculation with addition and multiplication and no grouping parentheses, Python does the multiplication first.

How

  1. Write 6 + 3 to count the pieces for one kit.
  2. Put parentheses around that addition to get (6 + 3).
  3. Put * 4 after the group to count four kits.

Worked example

Count the pieces in four kits

Python code
print((6 + 3) * 4)
print(6 + 3 * 4)

Standard input

Empty

Standard output

36
18

Type both lines into an editor and run the file with Python 3.13. The first line counts all parts of all four kits. The second counts the clips once and the rings four times.

The trap

Reading 6 + 3 * 4 strictly from left to right would give 36. Python does 3 * 4 first, which counts 12 rings, then adds six clips once, for 18 pieces. To count six clips in every kit, group the two counts as (6 + 3) * 4.

2.3 Keep a remainder

about 1 minOpen the full lesson

The rule

The total is how many items you start with.

It can be any whole number from zero up. The group size is how many items fit in one full group. It can be any whole number from one up. Here, whole numbers are the counts 0, 1, 2 and so on.

Put the total on the left and the group size on the right. With // between them, Python gives the number of full groups. With % between them, it gives the remainder. The remainder is smaller than the group size. When it is zero, the full groups use all the items.

How

  1. Write down the total and the group size.
  2. Use // between those numbers to find the number of full groups.
  3. Use % between the same numbers to find the remainder.
  4. Multiply the group count by the group size and add the remainder. Check that you get the total and that the remainder is smaller than one full group.
  5. When you type the program, cards = 38 gives the name cards the value 38. The line cards_per_sleeve = 6 gives the group size its own name, with underscores between the words.

Worked example

Pack 38 postcards

Python code
cards = 38
cards_per_sleeve = 6

print(cards // cards_per_sleeve)
print(cards % cards_per_sleeve)

Standard input

Empty

Standard output

6
2

Save the code as postcards.py and run the file. Count full sleeves on the first output line and loose cards on the second. As a second check, subtract 6 repeatedly from 38 to reach 32, 26, 20, 14, 8 and 2.

The trap

If you catch yourself reading % as “percent,” read 38 % 6 aloud as “How many cards are left?” Its answer counts two loose cards. If you swap the two results, you get two full sleeves and six loose cards. Six loose cards would fill one more sleeve, so the swap fails the remainder check.

2.4 Index and slice a label

about 1 minOpen the full lesson

The rule

With label as the name of the string, label[1] picks the character at index 1.

In label[2:5], 2 is the start and 5 is the stop. That takes positions 2, 3, and 4. When the start is smaller than the stop and both numbers are in the range from zero through the total number of characters, subtract the start from the stop to get the slice’s character count.

How

  1. Number the boxes from left to right, starting at 0.
  2. Give the text the name label on the first line. The equals sign = tells Python to use the name on the left for the text on the right.
  3. After label, put the position in square brackets for one character. For a slice, put the start and stop in the brackets with a colon between them.
  4. To display the result, put your selection inside the parentheses of print(). The text print() displays is the output. For these labels, print() displays the text without the surrounding quotes.
  5. In a text editor, type the three nonblank lines under Code in the worked example. Keep the blank line and start each line at the left edge. Run the file with Python 3.13. If you use the Python shell, where you can run one line at a time, type each nonblank source line after the >>> shown on screen and press Enter.

Worked example

Read the shelf tag

Python code
label = "RACK27"

print(label[1])
print(label[2:5])

Standard input

Empty

Standard output

A
CK2

Type the program in an editor and keep the blank line. Run the file. To check the slice on paper, cover RA before the start and 7 after the stop. The uncovered characters read CK2.

The trap

If you start numbering at 1, you’ll pick R for index 1. Label that first box 0 and the next box 1 to find A. If you include box 5 in the slice, you’ll get CK27. Place your pencil on the line before box 5 and leave the 7 on the far side.

2.5 Format a line of output

about 1 minOpen the full lesson

The rule

Put f right before the opening quote.

Inside the quotes, put the names whose values you want to use inside braces. Type the literal pieces where they should appear. Write :.2f after the number’s name inside its braces. For the lengths on these cards, .2f writes out two places after the decimal point, adding a zero or rounding the displayed number as needed.

In these examples, print(...) displays the finished text and then adds a newline, which ends the line.

How

  1. Give each value a name. Put the shelf name in quotes and write the length as a number. On each line, = gives the name on the left the value on the right.
  2. Inside print(...), start the template with f". Write {name} where the shelf name goes. Type a colon and one space after it.
  3. Add {length:.2f}, then one space and m. Type the closing quote and the closing parenthesis ).
  4. Predict the printed line. Read the name, the colon and space, the number with two digits after the decimal point, then the space and unit.

Worked example

Fill the Oak shelf card

Python code
name = "Oak"
length = 3.5

print(f"{name}: {length:.2f} m")

Standard input

Empty

Standard output

Oak: 3.50 m

Type the program into an editor and run the file. In the output, count two digits after the decimal point. Check the space after the colon and the space before m. The number assigned to length remains 3.5.

The trap

If you see braces in the printed line, check for the f before the opening quote. In this example, leaving it out makes Python print the text inside the quotes as written, braces and all. With the prefix in place, the format instruction controls the number’s appearance on the card. length still holds 3.5 after the program prints 3.50.

3 Decisions

about 9 min5 lessonsOpen the unit's crash course

3.1 Ask a true-or-false question

about 2 minOpen the full lesson

The rule

A comparison has a value on each side of a comparison operator.

When both sides are numbers, or both are strings, Python works out the two sides, asks the question and gives back True or False. <, <=, > and >= ask about order. == asks whether the two values are equal, and != asks whether they differ.

Two whole numbers are equal when they are the same number. Two strings are equal when they hold the same characters in the same order, so "Gate" == "gate" is False. A string and a whole number are never equal, so "6" == 6 is False. Asking about order between a string and a number, as in "6" < 7, stops the program with a TypeError.

How

  1. Say the question in words. For the boat program below, one question is whether the number of riders is more than the number of seats.
  2. Choose the operator that matches the words. "More than" is >. "At least" is >=. "Fewer than" is <. "At most" is <=. "Exactly" is ==. "Anything but" is !=.
  3. Check the types. A string and a whole number are never equal, so compare a number with a number and text with text. A value that came from input() is text. When that text is a whole number such as 6, int makes a number from it, as the second worked example shows.
  4. Work out each side to one value. Do any arithmetic first.
  5. Ask the question about those two values and write True or False.

Worked example

Ask three questions about a boat

Python code
seats = 4
riders = 6
print(riders > seats)
print(riders == seats + 2)
print(riders != 6)

Standard input

Empty

Standard output

True
True
False

Predict each of the three output lines first. Then save the five lines as boat.py and run the file, or follow the trace below. Each comparison works out to True or False, and the addition in the fourth line is done before its comparison.

Compare a typed reply

Python code
reply = input()
print(reply == 6)
print(int(reply) == 6)

Standard input

6

Standard output

False
True

Save the three lines as reply.py, run the file, type 6 and press Enter. The first comparison sets the text "6" against the number 6, and a string never equals a whole number. The second makes a number from the reply first, so two numbers are compared.

The trap

The usual slip is typing = where you mean ==. In the Shell, riders = 6 gives the name a value and shows nothing. riders == 6 asks the question and shows True or False. When a comparison shows nothing, count the equals signs.

A quieter slip is comparing text with a number. "6" == 6 is False, and Python raises no error to warn you. If the value came from input() and holds a whole number, make a number from it with int before you compare it with a number.

The two-character operators have one spelling each. Write >=, <= and != with the = second. => and =< are not Python operators. A file that holds one stops with a SyntaxError before its first line runs.

3.2 Choose a branch

about 2 minOpen the full lesson

The rule

Write if, a condition and a colon.

Indent the block beneath it, by four spaces in this course. Python runs the block only when the condition is true. An optional else: line, lined up with the if, has its own indented block, which runs only when the condition is false. Lines after the whole statement, back at the left margin, run in both cases.

How

  1. Write the decision as two sentences, the first starting with if and the second with otherwise. The baggage rule invented for this lesson reads: if the bag is over the weight limit, charge a fee. Otherwise, charge nothing.
  2. Turn the first sentence into an if line. Write if, then the condition, then a colon: if weight > 23:.
  3. On the next lines, indented by four spaces, write what happens when the condition is True.
  4. If something different happens otherwise, write else: lined up with if, and indent its lines by four spaces too.
  5. Return to the left margin for the lines that run in both cases.
  6. Trace the program twice, once with a value that makes the condition True and once with a value that makes it False.

Worked example

Type 30 for a bag over the limit

Python code
reply = input()
weight = int(reply)
if weight > 23:
    print("Heavy bag: pay the fee")
else:
    print("No fee")
print("Next traveler")

Standard input

30

Standard output

Heavy bag: pay the fee
Next traveler

Save the code as bag.py, run it, type 30 and press Enter. The condition 30 > 23 is True, so the first block runs and the else block is skipped.

Type 18 for a bag under the limit

Python code
reply = input()
weight = int(reply)
if weight > 23:
    print("Heavy bag: pay the fee")
else:
    print("No fee")
print("Next traveler")

Standard input

18

Standard output

No fee
Next traveler

Run the same file and type 18. The condition 18 > 23 is False, so Python skips the first block and runs the else block. The last line runs in both cases.

Leave the block at the margin

Python code
weight = 30
if weight > 23:
print("Heavy bag: pay the fee")

Standard input

Empty

Standard output

Empty

Exception IndentationError

The print line is not indented, so the if line has no block. Python reports an IndentationError that names line 3 and displays nothing, because it found the problem before running line 1. Indent line 3 by four spaces to repair it.

The trap

A line with the wrong indentation can still be a legal program. Take an if statement that has no else, and suppose its block should display two lines. Leave the second at the margin and Python reports no error. It treats that line as the first line after the if statement and runs it whatever the condition gave. Check the left edge of every line when a program does more than you expected.

When an else: follows, the same slip stops the program. A line at the margin ends the if statement, so the else: below it has no if to belong to, and Python reports a SyntaxError before any line runs.

A missing colon is caught before the program starts. if weight > 23 with no colon stops with a SyntaxError before any line runs, and the message marks the place in that line where Python found the problem.

Keep to four spaces for each level, and do not mix tabs with spaces. Start every statement of one block at the same depth. The blocks of statements nested inside it are indented further. A line whose depth fits no block stops the program with an IndentationError.

3.3 Handle a boundary value

about 2 minOpen the full lesson

The rule

In an if, elif, else chain Python works out the conditions in order and runs the block of the first one that is true.

No later branch is tested or run. If every condition is false, the else block runs, and if there is no else, no block of the chain runs.

<= and >= include the value they are compared with. < and > leave it out.

How

  1. List the values where the rule changes. In the parcel rule they are 2 and 10.
  2. For each one, read the words of the rule and decide which side the value itself belongs to. The rule says up to 2, so 2 stays with the lighter parcels.
  3. Use if for the first band, elif for each middle band and else for what is left. Put the conditions in order from one end of the range. The parcel program starts from the lowest cutoff.
  4. Pick test values: each boundary value and the whole number on the other side of the change. The rule keeps 2 in the lower band, so the other side starts at 3. It keeps 10 in the middle band, so the other side starts at 11. The test values are 2, 3, 10 and 11.
  5. Work out the expected price for each test value by hand, from the words of the rule.
  6. Run or trace the program with each test value and compare. A mismatch at a boundary points to < against <= or to the order of the conditions.

Worked example

Type 2, the first boundary value

Python code
reply = input()
weight = int(reply)
if weight <= 2:
    price = 4
elif weight <= 10:
    price = 9
else:
    price = 15
print(price)

Standard input

2

Standard output

4

Save the code as parcel.py, run it and type 2. The first condition, 2 <= 2, is True, so the price is 4 and Python skips the other two branches.

Type 10, the second boundary value

Python code
reply = input()
weight = int(reply)
if weight <= 2:
    price = 4
elif weight <= 10:
    price = 9
else:
    price = 15
print(price)

Standard input

10

Standard output

9

Run the file again and type 10. 10 <= 2 is False, so Python asks the elif condition. 10 <= 10 is True and the price is 9.

Type 11, the other side of the second boundary

Python code
reply = input()
weight = int(reply)
if weight <= 2:
    price = 4
elif weight <= 10:
    price = 9
else:
    price = 15
print(price)

Standard input

11

Standard output

15

Run the file once more and type 11. Both conditions are False, so the else block sets the price to 15.

The trap

Writing < where the rule needs <= moves one value to the wrong side. With weight < 2, a parcel with a weight of 2 costs 9 coins. Every other whole-number weight is still priced correctly, so the mistake shows only in a test with 2.

Using a second if where the rule needs elif is the other common slip. Two separate if statements are two separate decisions, and Python tests each one it reaches. With if weight <= 2: followed by if weight <= 10:, a parcel with a weight of 2 passes both, and the second block replaces the price of 4 with 9. An elif is tested only when every condition above it in the same chain was false.

3.4 Combine two conditions

about 2 minOpen the full lesson

The rule

When A and B are each True or False: A and B is True only if both are True.

A or B is True if at least one is True. not A is True if A is False, and False if A is True.

Without parentheses, comparisons group first, then not, then and, then or. Python works out the left side of and or or first, and works out the right side only when the left side has not settled the answer.

How

  1. Write the rule in words and underline each joining word: and, or, not.
  2. Write each part as a complete condition. A part is a comparison with its own left side, operator and right side, such as height >= 120, or a name that already holds True or False, such as has_ticket.
  3. Where the rule negates a part, write not in front of that part, such as not has_coat.
  4. Join the parts with and where both must hold and with or where one is enough.
  5. If the rule mixes and with or, put parentheses around the part the rule treats as one group, as in (member or total > 50) and coupon.
  6. Fill in a small table with one row for each case of the parts, True or False, and work out the whole condition for every row.

Worked example

Tall enough, with a ticket

Python code
height = int(input())
ticket = input()
has_ticket = ticket == "yes"
if height >= 120 and has_ticket:
    print("Board the ride")
else:
    print("Wait here")

Standard input

131
yes

Standard output

Board the ride

Save the code as ride.py, run it, type 131, press Enter, type yes and press Enter. The first line does two steps at once: input() hands back the typed text, and int makes a number from it. Both parts of the condition are True, so the whole condition is True.

Tall enough, without a ticket

Python code
height = int(input())
ticket = input()
has_ticket = ticket == "yes"
if height >= 120 and has_ticket:
    print("Board the ride")
else:
    print("Wait here")

Standard input

131
no

Standard output

Wait here

Run the file again and type 131, then no. The height part is True and the ticket part is False. and needs both, so the condition is False. A False condition sends Python to the else block.

Flip and join two named values

Python code
raining = True
has_coat = False
print(not raining)
print(raining and not has_coat)
print(raining or has_coat)

Standard input

Empty

Standard output

False
True
True

Save the five lines as rain.py. Predict the three output lines before you run the file. The middle line groups as raining and (not has_coat).

The trap

Each side of and or or must be an expression that stands on its own. English lets you say "older than 12 and younger than 18". In Python, < 18 is not an expression, so age > 12 and < 18 stops with a SyntaxError. Write age > 12 and age < 18.

The slip that raises no error is reply == "y" or "yes". Python reads it as (reply == "y") or "yes". The right side is the text "yes" on its own, and Python counts any text that is not empty as true. The condition therefore passes for every reply. Write reply == "y" or reply == "yes".

When and and or share a line, and groups more tightly. member or total > 50 and coupon means member or (total > 50 and coupon). If you mean the other grouping, write the parentheses.

3.5 Trace a ticket rule

about 1 minOpen the full lesson

The rule

A block may hold another if statement.

The inner statement's blocks are indented one level further, by four more spaces in this course. Python reaches the inner if only when the block that holds it runs. Each else or elif belongs to the if whose line starts at the same depth.

How

  1. Write the inputs for one test case at the top of a sheet, with the output you expect from the rule in words.
  2. Go down the program one line at a time. At an assignment, record the new value of the name.
  3. At an if or elif line, work out the condition with the current values and write True or False beside it.
  4. If it is True, move into the block beneath it. If it is False, skip every line indented further than that line and continue at the next line that is indented the same amount or less.
  5. After one block of an if statement has run, skip its remaining elif and else branches.
  6. Compare the output with what you expected. Repeat with further test cases until every block has run at least once.

Worked example

A member aged 16

Python code
age = int(input())
member = input() == "yes"
if age < 5:
    price = 0
else:
    if age < 16:
        price = 6
    else:
        price = 10
    if member:
        price = price - 2
print(f"Ticket: {price} coins")

Standard input

16
yes

Standard output

Ticket: 8 coins

Save the code as museum.py, run it, type 16, press Enter, type yes and press Enter. The trace below follows this run. 16 < 5 is False, so Python runs the outer else block, where the price becomes 10 and the member discount brings it to 8.

A member aged 3

Python code
age = int(input())
member = input() == "yes"
if age < 5:
    price = 0
else:
    if age < 16:
        price = 6
    else:
        price = 10
    if member:
        price = price - 2
print(f"Ticket: {price} coins")

Standard input

3
yes

Standard output

Ticket: 0 coins

Run the file again and type 3, then yes. 3 < 5 is True, so Python sets the price to 0 and skips the whole outer else block, including the member discount.

A visitor aged 15 who is not a member

Python code
age = int(input())
member = input() == "yes"
if age < 5:
    price = 0
else:
    if age < 16:
        price = 6
    else:
        price = 10
    if member:
        price = price - 2
print(f"Ticket: {price} coins")

Standard input

15
no

Standard output

Ticket: 6 coins

Run the file once more and type 15, then no. The outer condition is False, the inner condition 15 < 16 is True, and member is False, so the price stays 6.

The trap

Moving a line sideways can change which decision it belongs to, and Python accepts both versions. Suppose the whole if member: statement is moved four spaces to the left, so that its first line starts at the margin. It no longer sits inside the outer else block, so Python reaches the test for every visitor, and every member gets the discount. A member aged 3 then gets 0 - 2, and the program displays Ticket: -2 coins. Trace one case for each branch after you change any indentation.

A second slip is tracing only the case you had in mind when you wrote the code. The case you traced proves nothing about a visitor who takes a different branch. Check the list of test cases against the blocks, and add a case for any block that no test reaches.

4 Repeated work

about 6 min5 lessonsOpen the unit's crash course

4.1 Read a for loop

about 1 minOpen the full lesson

The rule

A for loop over a sequence runs its indented body once for each item, in order, unless a break ends it sooner.

Before each pass, the name after for is given the next item. When the items run out, the program carries on with the first line after the body. An empty sequence gives no passes.

How

  1. Find the sequence after in and write its items in order. A string gives one item for each character.
  2. Find the body: the lines indented under the for line.
  3. For each item, write the loop name's value, then run the body's lines in order with that value.
  4. After the last pass, move to the first line after the body. In this unit's programs that is the next line indented no further than the for line.
  5. Count the passes: one for each item, unless a break ends the loop sooner. Check that the output holds what the body displays once for each pass.

Worked example

Display each character of a string

Python code
for letter in "MAP":
    print(letter)
print("done")

Standard input

Empty

Standard output

M
A
P
done

Predict the four output lines first. Then save the code as letters.py and run the file, or follow the trace below. The body runs once for each of the three characters, and done is displayed once, after the loop.

A body of two lines

Python code
for letter in "ab":
    print(letter)
    print("-")
print("end")

Standard input

Empty

Standard output

a
-
b
-
end

Both print lines are indented, so both belong to the body and both run on each pass. The last line is at the margin, so it runs once.

The trap

A line meant to run once can slip into the body. If print("done") were indented under the for line, it would run on every pass and the output would hold done three times. Check the indentation of each line below a for line.

The loop name keeps its last value after the loop ends. After the loop over "MAP", letter still holds P. Use the loop name inside the body, where it holds the current item.

4.2 Choose the bounds of range

about 2 minOpen the full lesson

The rule

range(stop) gives the whole numbers from 0 up to but not including stop.

range(start, stop) starts at start when start is below stop, and is empty otherwise. range(start, stop, step) moves by step each time and holds the numbers below stop for a positive step, or above stop for a negative one. stop is never included, and a step of 0 raises a ValueError.

How

  1. Write the first number you want. That is start. It can be left out when it is 0 and no step is given, because a step needs a start before it.
  2. Choose the step. Leave it out to count up by 1, write a bigger number as the third number to skip, or a negative one to count down.
  3. Write the last number you want, and check that counting from start by the step lands on it; if it does not, change the start or the step. Then set stop past it, no more than one step beyond it: above it when counting up, below it when counting down. For a count up by 1, stop is the last number plus 1. In range(10, 0, -3) the last number is 1, and the stop 0 lies below it, within one step of 3.
  4. Check the count: for a step of 1 and a stop above start, range(start, stop) gives stop minus start numbers.
  5. Write out the numbers the range gives, or note that it gives none, and compare them with what you wanted.

Worked example

Count from 1 to 5

Python code
for n in range(1, 6):
    print(n)

Standard input

Empty

Standard output

1
2
3
4
5

The last number wanted is 5, so stop is 6. Save the code as count.py and run the file.

Count down by 3

Python code
for n in range(10, 0, -3):
    print(n)

Standard input

Empty

Standard output

10
7
4
1

The step is -3, so each number is 3 less than the one before. The trace below shows why the loop ends after 1.

Number three laps from 1

Python code
for lap in range(1, 4):
    print(f"Lap {lap}")

Standard input

Empty

Standard output

Lap 1
Lap 2
Lap 3

range(1, 4) gives 1, 2 and 3: three numbers, starting at 1 and stopping before 4.

Give range a step of zero

Python code
for n in range(0, 10, 0):
    print(n)

Standard input

Empty

Standard output

Empty

Exception ValueError

Save the two lines as zero.py and run the file. The program stops with a ValueError at the for line, before the body runs once.

The trap

The usual slip is a stop one short. range(1, 5) ends at 4, so a loop meant to count to 5 needs range(1, 6). Write out the last number of the range before you run the program.

Counting down needs a negative step. range(5, 1) holds no numbers, because its step is 1 and 5 is not below 1. The loop makes no passes and nothing is displayed. Write range(5, 1, -1) for 5, 4, 3 and 2.

4.3 Trace a while loop

about 1 minOpen the full lesson

The rule

A while loop tests its condition before every pass.

While the condition is true, it runs the indented body and, when the body reaches its end, goes back to the test; a break ends it sooner. When the condition is false, the program carries on with the first line after the body, and a condition that is false at the first test gives no passes.

How

  1. Write each name the condition uses, with its value before the loop.
  2. Test the condition with those values. If it is false, skip to the first line after the body.
  3. If it is true, run the body's lines in order and write each name's new value.
  4. Find what can make the condition false at a later test: a line in the body that changes a name it reads, or a new value it reads each time, such as a reply from input(). If nothing can, and nothing else ends the loop, such as the break of this unit's last lesson, the loop will not end on its own.
  5. Go back to the test with the new values, and repeat until a test is false or something ends the loop sooner.

Worked example

Count down to Go

Python code
seconds = 3
while seconds > 0:
    print(seconds)
    seconds = seconds - 1
print("Go")

Standard input

Empty

Standard output

3
2
1
Go

Predict the four lines first. Then save the code as countdown.py and run the file, or follow the trace below.

Save until the goal is reached

Python code
balance = 50
weeks = 0
while balance < 100:
    balance = balance + 20
    weeks = weeks + 1
print(weeks)
print(balance)

Standard input

Empty

Standard output

3
110

The program does not know in advance how many weeks it takes. After 3 weeks the balance is 110. That is not below 100, so the loop ends, one week past 90.

Ask again until the reply is right

Python code
guess = input()
while guess != "blue":
    print("Try again")
    guess = input()
print("Yes")

Standard input

red
green
blue

Standard output

Try again
Try again
Yes

Type red, green and blue, one a line. The first two replies keep the condition true. blue makes it false, so the loop ends and Yes is displayed.

The trap

Leave out the line that changes the name, and the condition never becomes false. A countdown without seconds = seconds - 1 displays 3 again and again and never ends. Press Control-C, the interrupt key, to stop it; Python stops the program with a KeyboardInterrupt.

The other slip is the edge of the condition. seconds > 0 stops before 0 is displayed, and seconds >= 0 displays 0 as well. Trace the last two tests to see which values get a pass.

4.4 Keep a running total

about 1 minOpen the full lesson

The rule

A running total or a count is set to its starting value before the loop and changed inside the body, so each pass builds on the last.

The biggest value so far starts with the first value and is replaced inside the loop when an if finds a bigger one. x += 1 adds 1 to x.

How

  1. Decide what to keep: a total, a count or the biggest value.
  2. Before the loop, give it a starting value: 0 for a total or a count, the first value for the biggest. A line such as total = total + steps reads the name before it changes it, so the name needs a value first.
  3. Inside the body, change it on the passes that need it: add each value to a total, add 1 when a pass matches, or replace the biggest when an if finds a bigger value.
  4. After the loop, use the result: display it, or, when the count is above 0, divide the total by the count for an average.
  5. Trace two passes by hand and check that the value after each pass builds on the one before.

Worked example

Add up four days of steps

Python code
total = 0
for day in range(4):
    steps = int(input())
    total = total + steps
average = total / 4
print(f"Total: {total}")
print(f"Average: {average}")

Standard input

4000
6500
5500
4000

Standard output

Total: 20000
Average: 5000.0

Type the four numbers one a line, or follow the table above. Each pass reads one number and adds it to the total. The average is worked out in a name of its own before it is displayed.

Keep the biggest score so far

Python code
biggest = int(input())
for turn in range(3):
    score = int(input())
    if score > biggest:
        biggest = score
print(biggest)

Standard input

12
40
33
40

Standard output

40

The first score, 12, is the biggest so far. 40 replaces it. 33 and the second 40 are not bigger than 40, so biggest does not change, though score does.

Count the letter a

Python code
count = 0
for ch in "banana":
    if ch == "a":
        count += 1
print(count)

Standard input

Empty

Standard output

3

The count goes up by 1 only on the passes where the character is a, because the if runs its block only then. banana has three of them.

The trap

A total set to 0 at the top of the body starts again on every pass. With total = 0 as the body's first line, the step program would display Total: 4000, the last day's steps alone, and Average: 1000.0, that one day divided by 4. Put the starting value above the for line.

Starting the biggest value at 0 goes wrong when every value is below 0: no value is bigger than 0, so the program would display 0, a number that was never read. Start with the first value instead, as the worked example does.

4.5 Stop a search at a match

about 1 minOpen the full lesson

The rule

A break line ends the nearest loop around it at once, skips the rest of that pass and every later pass, and the program carries on with the first line after the loop.

After a break, a for loop's name keeps its current item.

How

  1. Above the loop, set any name that the program reads after the loop and that only a match changes, such as found = False.
  2. Write the test that marks a match, and put it in an if inside the body.
  3. Inside that if, do what the match needs, such as setting found = True, and then write break.
  4. Trace the passes until the test is true. At the break, jump to the first line after the loop.
  5. Check the case with no match. A for loop runs to its end, and a name that only a match changes, such as found, still holds the value it was given above the loop. A while True: loop that reads input and meets no match keeps reading; when the input runs out, input() stops the program with an EOFError.

Worked example

Stop at the first space

Python code
for ch in "plan B":
    if ch == " ":
        print("space found")
        break
    print(ch)
print("after")

Standard input

Empty

Standard output

p
l
a
n
space found
after

Predict the output first. Then save the code as space.py and run the file. The B after the space is never displayed, because the loop ends at the space.

Read words until done

Python code
count = 0
while True:
    word = input()
    if word == "done":
        break
    count = count + 1
print(count)

Standard input

fern
moss
done
ivy

Standard output

2

The input holds four lines: fern, moss, done and ivy. The loop counts two words and ends at done, so ivy is never read.

Find the first square over 200

Python code
found = False
for n in range(1, 50):
    if n * n > 200:
        found = True
        break
print(found)
print(n)

Standard input

Empty

Standard output

True
15

14 times 14 is 196 and 15 times 15 is 225, so the search stops at 15. After the break, n still holds 15.

The trap

A message about a miss written in the body after the match test runs on every pass that misses: in a search for a space, once for each character before the space, or once for every character of a string with no space. Decide after the loop, with a name such as found, whether the search found nothing.

In a while True: loop, the test never ends the loop. If the test before the break is never true for the replies typed, as when each reply is compared with "Done" and the person types done each time, the loop keeps asking. It stops only with an error: an EOFError when the input runs out, or a KeyboardInterrupt when you press Control-C, the interrupt key.

5 Lists and dictionaries

about 4 min5 lessonsOpen the unit's crash course

5.1 Build an ordered list

about 1 minOpen the full lesson

The rule

A list is written as values between square brackets, separated by commas, and keeps them in order.

a[i] gives the item at index i, counted from 0; a[-1] gives the last item; len(a) gives the number of items. An index from len(a) up raises an IndexError.

How

  1. Write the items in order between square brackets, separated by commas.
  2. Number the items from 0 under the list as you trace it.
  3. Before reading an item, check its index against the length: in a list that is not empty, the largest index is one less than len(), and an empty list has no item to read.
  4. To read an item, use its number in square brackets after the list's name. Use -1 for the last item.
  5. To work through every item, write a for loop over the list.

Worked example

Read a list by index and by loop

Python code
queue = ["Ada", "Ben", "Cy"]
print(queue[0])
print(queue[-1])
print(len(queue))
for name in queue:
    print(f"Next: {name}")

Standard input

Empty

Standard output

Ada
Cy
3
Next: Ada
Next: Ben
Next: Cy

Predict the six output lines first. Then save the code as queue.py and run the file. queue[0] is the first item, queue[-1] the last, and the loop visits the items in order.

Ask for an index past the end

Python code
queue = ["Ada", "Ben", "Cy"]
print(queue[3])

Standard input

Empty

Standard output

Empty

Exception IndexError

Save the two lines as end.py and run the file. The list has items at 0, 1 and 2, so index 3 is out of range and the program stops with an IndexError.

The trap

The usual slip is counting from 1. In a list of 3 items, queue[3] is not the last item: it is past the end, and the program stops with an IndexError. Use queue[2], or queue[-1].

Square brackets do two jobs here. In ["Ada", "Ben"] they make a list; after a name, as in queue[0], they read an item.

5.2 Update an item by index

about 1 minOpen the full lesson

The rule

A list is mutable.

a[i] = v replaces the item at index i with v and keeps the length; a.append(v) adds v at the end and makes the list one item longer. A string is immutable: assigning to one of its characters raises a TypeError.

How

  1. Write the list with each index under its item.
  2. Before name[i] = value, check that index i names an item: for a list of n items, from 0 up to n - 1, or from -1 back to -n counting from the end.
  3. For name[i] = value, cross out the item at index i and write the new value there.
  4. For name.append(value), write the value after the last item and add 1 to the length.
  5. Print the list to see its items after the changes, and print len() of it to see how many items it holds.

Worked example

Replace an item and add one

Python code
scores = [7, 4, 9]
scores[1] = 6
scores.append(10)
print(scores)
print(len(scores))

Standard input

Empty

Standard output

[7, 6, 9, 10]
4

Predict the two output lines first, then run the file. The second score changes from 4 to 6, and 10 joins the end.

Try to change one character of a string

Python code
code = "cat"
code[0] = "b"

Standard input

Empty

Standard output

Empty

Exception TypeError

Save the two lines as code.py and run the file. A string cannot be changed, so the second line stops the program with a TypeError. Build a new string instead.

The trap

Assigning the result of append to the list's name loses that name for the list. append changes the list and gives back None, so after scores = scores.append(10) the list has grown, but scores names None.

To add an item, use append, not an index one past the end: scores[3] = 10 on a list of three items stops with an IndexError.

5.3 Look up a key

about 1 minOpen the full lesson

The rule

A dictionary holds key: value pairs with unique keys.

d[k] gives the value stored with key k, and a missing key raises a KeyError. d[k] = v adds the pair, or replaces the value when k is already a key. k in d is True when k is a key.

How

  1. Write each key with its value, in pairs, as the dictionary is built.
  2. For d[k] = v, replace the value if k is already a key; otherwise add the new pair at the end, since the keys keep the order they were added in.
  3. For d[k], find the key and read its value; if the key is missing, the program stops with a KeyError.
  4. For k in d, answer True when k is one of the keys, and False otherwise.

Worked example

Store, replace and read by key

Python code
phone = {"Ada": 4098, "Ben": 4139}
phone["Cy"] = 4127
phone["Ada"] = 4100
print(phone["Ada"])
print(phone)
print("Ben" in phone)

Standard input

Empty

Standard output

4100
{'Ada': 4100, 'Ben': 4139, 'Cy': 4127}
True

Predict the three output lines first, then run the file. Cy is a new key, so its pair is added; Ada is already a key, so its value is replaced. Python prints the text keys with single quotation marks.

Read a key that is not there

Python code
phone = {"Ada": 4098}
print(phone["Dee"])

Standard input

Empty

Standard output

Empty

Exception KeyError

Save the two lines as dee.py and run the file. Dee is not a key, so the program stops with a KeyError.

The trap

Reading a key that was never stored stops the program with a KeyError. When a key may be missing, test it with in first.

A dictionary is not read by position. phone[0] looks for the key 0, not the first pair, and here it stops with a KeyError because 0 is not one of its keys.

5.4 Count repeated labels

about 1 minOpen the full lesson

The rule

To count labels, start with an empty dictionary.

For each label, add 1 to its value when it is already a key, and store it with 1 when it is not. After the loop, each key's value is the number of times that label appeared.

How

  1. Set counts = {} above the loop.
  2. Loop over the labels with a for loop.
  3. Inside the loop, test if label in counts:.
  4. When it is true, write counts[label] += 1; otherwise write counts[label] = 1, which stores the new key.
  5. After the loop, read a count with counts[label] or print the whole dictionary.

Worked example

Count five votes

Python code
votes = ["tea", "milk", "tea", "water", "tea"]
counts = {}
for vote in votes:
    if vote in counts:
        counts[vote] += 1
    else:
        counts[vote] = 1
print(counts)
print(counts["tea"])

Standard input

Empty

Standard output

{'tea': 3, 'milk': 1, 'water': 1}
3

Predict the two output lines first, then run the file. tea is counted three times; milk and water once each, and the keys appear in the order they were first stored.

The trap

Writing only counts[vote] += 1 stops at the first vote with a KeyError, because the count is read before anything was stored for that key. The else branch stores the first 1.

Setting counts = {} inside the loop empties the tally on every pass, and only the last vote would be left. Put it above the loop.

5.5 Choose a list or dictionary for a roster

about 1 minOpen the full lesson

The rule

Use a list when the order or position of values matters, and read it by index.

Use a dictionary when values are looked up by a key such as a name, and read it by key. Keys of a dictionary are unique; values and list items may repeat.

How

  1. Write the questions the program must answer.
  2. If a question asks by position, such as first or next, keep a list.
  3. If a question asks by a name or code, keep a dictionary with that name as the key.
  4. Check the keys: each key holds one value only.
  5. Use both when the program needs both kinds of question.

Worked example

Keep a seating list and a room dictionary

Python code
seats = ["Ada", "Ben", "Cy"]
rooms = {"Ada": "B2", "Ben": "A1", "Cy": "B2"}
print(seats[1])
print(rooms["Cy"])
seats.append("Dee")
rooms["Dee"] = "A1"
print(seats)
print(rooms["Dee"])

Standard input

Empty

Standard output

Ben
B2
['Ada', 'Ben', 'Cy', 'Dee']
A1

Predict the four output lines first, then run the file. The list answers who sits second; the dictionary answers Cy's room without counting along. Dee is added to both.

The trap

Using a name as a list index stops the program: seats["Cy"] raises a TypeError, because a list index is a whole number. Keep a dictionary for lookups by name.

Using one dictionary for values that share a key loses one of them: storing a second value with the same key replaces the first.

6 Functions

about 6 min5 lessonsOpen the unit's crash course

6.1 Give a repeated task a name

about 1 minOpen the full lesson

The rule

A def line and its indented body define a function without running the body.

The functions of this lesson have no parameters. Once such a function has been defined, a call, written as its name followed by an empty pair of parentheses, runs the body from its first line. When the body finishes, the program carries on from the place of the call. Each such call runs the body once.

How

  1. Find the lines that the program needs in more than one place.
  2. Write def, a name that says what the lines do, an empty pair of parentheses and a colon.
  3. Put the lines under the def line and indent them one more level, four spaces, keeping any deeper indentation they already have.
  4. Leave the indented block, and write the function's name with parentheses at each place where the lines should run.
  5. Trace the program: skip the body at the def line, and run the body at each call.

Worked example

Call one function twice

Python code
def show_banner():
    print("============")
    print("LOST AND FOUND")
    print("============")

show_banner()
print("Blue scarf")
show_banner()

Standard input

Empty

Standard output

============
LOST AND FOUND
============
Blue scarf
============
LOST AND FOUND
============

Predict the seven output lines first. Then save the code as banner.py and run the file, or follow the trace below. The body runs once for each call.

Call the function too early

Python code
show_banner()

def show_banner():
    print("LOST AND FOUND")

Standard input

Empty

Standard output

Empty

Exception NameError

Save the four lines as early.py and run the file. The call is on line 1, above the def line, so Python does not know the name yet and stops with a NameError. Move the call below the function to repair the program.

The trap

The parentheses make the call. On a line below the function's definition, the name alone, show_banner with no parentheses, does not call it. The file displays no banner and reports no error. Check for the parentheses when a function seems to do nothing.

The body belongs to the function only while it is indented. A print line at the margin, after the body, is not part of the function. It runs once, when Python reaches it, and not at each call.

6.2 Pass an argument

about 1 minOpen the full lesson

The rule

A parameter is a name in the parentheses of a def line, and an argument is a value in the parentheses of a call.

For the calls in this unit, Python works out the arguments, ties them to the parameters in order and then runs the body. For the functions defined in this unit, a call with fewer arguments than parameters stops with a TypeError.

How

  1. Find the value in the body that should change from call to call.
  2. Give that value a name and write the name inside the parentheses of the def line. For two values, write two names with a comma between them.
  3. Use the names in the body where the values were.
  4. In each call, write the values inside the parentheses in the same order as the names.
  5. Trace a call by writing each parameter with the argument it received, then running the body with those values.

Worked example

Greet two guests with one function

Python code
def greet(name):
    print(f"Welcome, {name}")

greet("Ada")
greet("Sam")

Standard input

Empty

Standard output

Welcome, Ada
Welcome, Sam

Predict the two output lines first. Then save the code as greet.py and run the file. Each call ties the parameter name to its own argument.

Pass two arguments in order

Python code
def label(item, count):
    print(f"{count} x {item}")

label("pens", 3)
label(3, "pens")

Standard input

Empty

Standard output

3 x pens
pens x 3

Predict the two output lines first. Then save the code as label.py and run the file. The second call gives the arguments in the other order, so item holds 3 and count holds the text. Python reports no error, and the label comes out the wrong way around.

Leave an argument out

Python code
def greet(name):
    print(f"Welcome, {name}")

greet()

Standard input

Empty

Standard output

Empty

Exception TypeError

Save the four lines as missing.py and run the file. The call supplies no argument for name, so Python stops with a TypeError before the body runs.

The trap

Arguments in the wrong order are the quiet mistake. label(3, "pens") is a legal call, and the program displays pens x 3. Check each call against the order of the names in the def line.

A second slip is to put quotation marks around a parameter's name in the body. Quotation marks make text, so print("name") displays the word name for every guest. Write the name without quotation marks, or inside the braces of an f-string, to use the value it holds.

6.3 Return a result

about 1 minOpen the full lesson

The rule

A return line works out its expression, ends the call and gives that value back to the calling line; a return with no expression gives back None.

A call whose body runs to its end without reaching a return line gives back None, and that includes a body that prints its result.

How

  1. Decide what value the rest of the program needs from the function.
  2. Write return followed by that value, or by the expression that works it out, at each point where the function's work is done. In the first worked example that is the last line of the body.
  3. At the call, do something with the value: give it a name, print it or use it in an expression.
  4. Trace a call by replacing it with the value it returns, then finishing the line the call was in.
  5. If a function should only display something, leave return out and call it on a line of its own.

Worked example

Use a returned price twice

Python code
def total_price(price, count):
    return price * count

bill = total_price(4, 3)
print(bill)
print(total_price(2, 5) + 1)

Standard input

Empty

Standard output

12
11

Predict the two output lines first. Then save the code as price.py and run the file, or follow the trace below. Each call is replaced by the value it returns.

Print in one function and return from another

Python code
def show_double(n):
    print(n * 2)

def give_double(n):
    return n * 2

result = show_double(5)
print(result)
print(give_double(5))

Standard input

Empty

Standard output

10
None
10

Predict the three output lines first. Then save the code as double.py and run the file. The body of show_double displays 10. It has no return line, so the call gives back None, and that is what the second output line shows. give_double displays nothing itself. It returns 10, and the last line prints that value.

Leave a function at the first return

Python code
def late_fee(days):
    if days == 0:
        return 0
    return 2

print(late_fee(0))
print(late_fee(4))

Standard input

Empty

Standard output

0
2

Predict the two output lines first. Then save the code as fee.py and run the file. For 0 days the condition is True and the first return line ends the call, so the second is never reached. For 4 days the condition is False, the indented block is skipped and the call ends at the second return line.

The trap

Printing inside a function is not returning. A function whose body prints its result and has no return line gives back None. A line such as total = show_double(5) + 1 then displays 10 and stops with a TypeError when Python tries to add None and 1. A TypeError is the error for an operation applied to a value of the wrong type. Use return when the calling line needs the value.

The opposite slip is to return a value and drop it. A line that holds only total_price(4, 3) runs the function, and in a file that is run it displays nothing. Python writes out the value of such a line only when the line is typed in the Shell and the value is not None.

6.4 Trace a local name

about 2 minOpen the full lesson

The rule

A parameter, and any name assigned anywhere in a function's body, is local to one call of that function.

A name that is neither a parameter nor assigned in the body is looked up among the global names, and after those among Python's built-in names. An assignment in the body makes or changes a local name and leaves a global name of the same spelling as it was. Outside the function the local names do not exist.

How

  1. Draw two columns for names: one for the file's global names and one for the call's local names.
  2. At a call, start a fresh local column and write each parameter in it with the argument it received.
  3. When the body uses a parameter or a name that it assigns, read it from the local column. If that local name has no value yet on that line, the program stops with an UnboundLocalError. For any other name, read the global column, and after that Python's built-in names such as print.
  4. At an assignment inside the body, first work out the right side, reading each name as the step before says. Then write or change the name on the left in the local column. Leave the global column alone.
  5. At a return line, work out the value to give back while the local column is still there.
  6. When the call ends, cross out the whole local column. If the rest of the program needs the returned value, give it a name at the call.

Worked example

Assign a name that also exists outside

Python code
count = 5

def reset():
    count = 0
    print(count)

reset()
print(count)

Standard input

Empty

Standard output

0
5

Predict the two output lines first. Then save the code as counter.py and run the file, or follow the trace below. The assignment in the body makes a local name, and the global name keeps its value.

Use a local name outside its function

Python code
def add_tip(bill):
    tip = 2
    return bill + tip

print(add_tip(10))
print(tip)

Standard input

Empty

Standard output

12

Exception NameError

Predict what happens on each of the last two lines first. Then save the code as tip.py and run the file. The call returns 12, which is displayed. The last line asks for tip outside the function, where no such name exists, and the program stops with a NameError.

Read a global name inside a function

Python code
rate = 3

def cost(hours):
    return hours * rate

print(cost(4))

Standard input

Empty

Standard output

12

Predict the output line first. Then save the code as rate.py and run the file. The body assigns nothing to rate, so Python finds no local name of that spelling and uses the global one.

The trap

The common surprise is expecting an assignment inside a function to change a global name. In the counter program the global count still holds 5 after reset() has run. To change a value for the rest of the program, have the function return the new value and assign it at the call. With a reset whose body ends in return 0, the line count = reset() gives the global count the value 0.

A sharper form of the same slip is a line such as count = count + 1 inside a function, with count assigned only at the margin. The assignment makes count local, so the right side asks for a local name that has no value yet, and the program stops with an UnboundLocalError, which is a kind of NameError. Pass the value in as an argument and return the result.

6.5 Compose two small functions

about 1 minOpen the full lesson

The rule

Python works out every argument of a call before the call begins.

When an argument is itself a call, that call finishes first and its return value becomes the argument of the call that receives it. For the receiving call to get a value other than None, the inner function has to return one.

How

  1. Write the task as a list of small jobs, each one taking some values and giving one value back.
  2. Write one function for each job, with a parameter for each value it takes. Return its result.
  3. Test each function that calls no other function alone, with a few arguments, including any boundary value. Compare with results worked out by hand.
  4. Join the functions by passing one call as the argument of another, or by giving a result a name and passing the name. Then test the joined function in the same way.
  5. Trace a joined line by working out each argument before the call that receives it, and replace each finished call with the value it returns.

Worked example

Join three functions into a receipt

Python code
def subtotal(price, count):
    return price * count

def with_fee(amount):
    if amount < 20:
        return amount + 3
    return amount

def receipt(price, count):
    total = with_fee(subtotal(price, count))
    return f"Total: {total} coins"

print(receipt(4, 3))
print(receipt(6, 5))

Standard input

Empty

Standard output

Total: 15 coins
Total: 30 coins

Predict the two output lines first. Then save the code as receipt.py and run the file, or follow the trace below. In each call of receipt, subtotal runs before with_fee.

Test one function alone at its boundary

Python code
def with_fee(amount):
    if amount < 20:
        return amount + 3
    return amount

print(with_fee(19))
print(with_fee(20))

Standard input

Empty

Standard output

22
20

Predict the two output lines first. Then save the code as fee_test.py and run the file. 19 is under 20, so the fee is added. 20 is not under 20, so the indented return line is skipped and the amount comes back unchanged.

The trap

A function that prints where it should return breaks the chain. If subtotal displayed the product and had no return line, with_fee would receive None. The comparison None < 20 would then stop the program with a TypeError, because Python provides no order comparison between None and a number. Return from every function whose value another function needs.

The other slip is one long function that does every job. Split it where one value is finished and the next job begins, so that each job can be called and tested by its own name.