Quarry School

Programming in Python: study guide

about 21 min to listen6 units30 lessonsevery crash course: about 37 min

The units in study order. For each: what it asks, every rule, every trap, and its crash course.

1 First programs

crash course: about 6 min5 lessons0 questions to tryOpen the crash course

What it asks. Write and run short Python programs, trace how values change and use error messages to fix a line.

Rule Run your first Python program

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.

Trap Run your first Python program

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.

Rule Tell text from numbers

Use addition for two integers and joining for two strings.

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

Trap Tell text from numbers

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.

Rule Give a value a name

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.

Trap Give a value a name

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.

Rule Read a reply from the keyboard

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.

Trap Read a reply from the keyboard

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.

Rule Use an error message to fix a program

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.

Trap Use an error message to fix a program

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

crash course: about 5 min5 lessons0 questions to tryOpen the crash course

What it asks. Calculate with numbers, select part of a string and format a line of output. Predict each result before you run the program.

Rule Choose an arithmetic operator

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.

Trap Choose an arithmetic operator

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.

Rule Group a calculation

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.

Trap Group a calculation

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.

Rule Keep a remainder

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.

Trap Keep a remainder

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.

Rule Index and slice a label

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.

Trap Index and slice a label

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.

Rule Format a line of output

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.

Trap Format a line of output

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

crash course: about 9 min5 lessons0 questions to tryOpen the crash course

What it asks. Ask a true-or-false question about a value, run one block of lines or another, and test the values where a rule changes. Predict each result before you run the program.

Rule Ask a true-or-false question

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.

Trap Ask a true-or-false question

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.

Rule Choose a branch

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.

Trap Choose a branch

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.

Rule Handle a boundary value

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.

Trap Handle a boundary value

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.

Rule Combine two conditions

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.

Trap Combine two conditions

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.

Rule Trace a ticket 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.

Trap Trace a ticket rule

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

crash course: about 6 min5 lessons0 questions to tryOpen the crash course

What it asks. Repeat a block of lines with for and while loops. Choose where a range starts and stops, keep a running total and stop a search at the first match, and predict each result before you run the program.

Rule Read a for loop

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.

Trap Read a for loop

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.

Rule Choose the bounds of range

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.

Trap Choose the bounds of range

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.

Rule Trace a while loop

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.

Trap Trace a while loop

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.

Rule Keep a running total

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.

Trap Keep a running total

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.

Rule Stop a search at a match

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.

Trap Stop a search at a match

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

crash course: about 4 min5 lessons0 questions to tryOpen the crash course

What it asks. Keep many values under one name: a list in order, and a dictionary by key. Change an item, look up a key, count repeated labels, and choose the right one for a job.

Rule Build an ordered list

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.

Trap Build an ordered list

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.

Rule Update an item by index

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.

Trap Update an item by index

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.

Rule Look up a key

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.

Trap Look up a key

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.

Rule Count repeated labels

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.

Trap Count repeated labels

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.

Rule Choose a list or dictionary for a roster

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.

Trap Choose a list or dictionary for a roster

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

crash course: about 6 min5 lessons0 questions to tryOpen the crash course

What it asks. Give a block of lines a name, pass it values and get a result back. Trace what each name holds inside and outside the function, and predict each result before you run the program.

Rule Give a repeated task a name

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.

Trap Give a repeated task a name

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.

Rule Pass an argument

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.

Trap Pass an argument

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.

Rule Return a result

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.

Trap Return a result

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.

Rule Trace a local name

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.

Trap Trace a local name

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.

Rule Compose two small functions

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.

Trap Compose two small functions

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.