Programming in Python overview
Read the units in order. Open rules, recipes and traps from their lessons.
First programs
- Run your first Python program
- Tell text from numbers
- Give a value a name
- Read a reply from the keyboard
- Use an error message to fix a program
The unit at a glance
Rules
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.
Use addition for two integers and joining for two strings. Check for quote marks before deciding which operation this example uses.
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.
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.
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.
Recipes
- 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.
- In the Shell, after the
>>>prompt, typeprint("Lantern")and press Return. The Shell shows Lantern. - Choose File, then New File, to open an empty editor window.
- In the editor window, type
print("Lantern")on line 1. Type the instruction only, without>>>. - 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.
- 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.
- Look at the Shell. You see a line containing RESTART, then Lantern, then the prompt.
- 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.
- Find the
+and the value on each side of it. In this lesson both values always have the same type. - Look at the edges of each value for a pair of matching quote marks.
- If both values have quotes, they are strings: write the characters of the left value, then the characters of the right value.
- If neither value has quotes, they are integers: add them as you would on paper.
- Write what
printshows: the result with no quote marks, on a line of its own.
- 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.
- 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.
- Write that result in the column of the name on the left. Carry every other name's value down unchanged from the row above.
- 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. - 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.
- Type the Python source, the lines of code shown below, in your editor. Keep the blank line after
reply = input()and save the file. - 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 digits04where the program is running and press Enter. - 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.
- 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.
- 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.
- Make one change in the Editor and save the file.
- Choose Run Module again and compare what appears in the Shell with your predicted output.
Traps
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.
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.
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.
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.
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.
Quantities and text
- Choose an arithmetic operator
- Group a calculation
- Keep a remainder
- Index and slice a label
- Format a line of output
The unit at a glance
Rules
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.
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.
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.
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.
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.
Recipes
- Say what is happening. Are you adding a piece, taking one away, finding the total of equal groups or sharing equally?
- Choose the operator for that action. Put it between the two numbers in the order described above.
- To show the result, type
printand put the calculation inside the parentheses(and). Type the source lines below in a file in your editor. Save it asribbon.pyand run it with Python 3.13. You can also follow along on paper with the printed trace, which shows the results in order.
- Write
6 + 3to count the pieces for one kit. - Put parentheses around that addition to get
(6 + 3). - Put
* 4after the group to count four kits.
- Write down the total and the group size.
- Use
//between those numbers to find the number of full groups. - Use
%between the same numbers to find the remainder. - 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.
- When you type the program,
cards = 38gives the namecardsthe value 38. The linecards_per_sleeve = 6gives the group size its own name, with underscores between the words.
- Number the boxes from left to right, starting at 0.
- Give the text the name
labelon the first line. The equals sign=tells Python to use the name on the left for the text on the right. - 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. - To display the result, put your selection inside the parentheses of
print(). The textprint()displays is the output. For these labels,print()displays the text without the surrounding quotes. - 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.
- 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. - Inside
print(...), start the template withf". Write{name}where the shelf name goes. Type a colon and one space after it. - Add
{length:.2f}, then one space andm. Type the closing quote and the closing parenthesis). - 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.
Traps
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.
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.
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.
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.
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.
Decisions
- Ask a true-or-false question
- Choose a branch
- Handle a boundary value
- Combine two conditions
- Trace a ticket rule
The unit at a glance
Rules
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.
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.
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.
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.
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.
Recipes
- 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.
- Choose the operator that matches the words. "More than" is
>. "At least" is>=. "Fewer than" is<. "At most" is<=. "Exactly" is==. "Anything but" is!=. - 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 as6,intmakes a number from it, as the second worked example shows. - Work out each side to one value. Do any arithmetic first.
- Ask the question about those two values and write
TrueorFalse.
- 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.
- Turn the first sentence into an
ifline. Writeif, then the condition, then a colon:if weight > 23:. - On the next lines, indented by four spaces, write what happens when the condition is True.
- If something different happens otherwise, write
else:lined up withif, and indent its lines by four spaces too. - Return to the left margin for the lines that run in both cases.
- Trace the program twice, once with a value that makes the condition True and once with a value that makes it False.
- List the values where the rule changes. In the parcel rule they are 2 and 10.
- 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.
- Use
iffor the first band,eliffor each middle band andelsefor what is left. Put the conditions in order from one end of the range. The parcel program starts from the lowest cutoff. - 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.
- Work out the expected price for each test value by hand, from the words of the rule.
- 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.
- Write the rule in words and underline each joining word: and, or, not.
- 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 holdsTrueorFalse, such ashas_ticket. - Where the rule negates a part, write
notin front of that part, such asnot has_coat. - Join the parts with
andwhere both must hold and withorwhere one is enough. - If the rule mixes
andwithor, put parentheses around the part the rule treats as one group, as in(member or total > 50) and coupon. - 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.
- Write the inputs for one test case at the top of a sheet, with the output you expect from the rule in words.
- Go down the program one line at a time. At an assignment, record the new value of the name.
- At an
iforelifline, work out the condition with the current values and write True or False beside it. - 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.
- After one block of an
ifstatement has run, skip its remainingelifandelsebranches. - Compare the output with what you expected. Repeat with further test cases until every block has run at least once.
Traps
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.
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.
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.
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.
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.
Repeated work
- Read a for loop
- Choose the bounds of range
- Trace a while loop
- Keep a running total
- Stop a search at a match
The unit at a glance
Rules
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.
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.
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.
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.
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.
Recipes
- Find the sequence after
inand write its items in order. A string gives one item for each character. - Find the body: the lines indented under the
forline. - For each item, write the loop name's value, then run the body's lines in order with that value.
- 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
forline. - Count the passes: one for each item, unless a
breakends the loop sooner. Check that the output holds what the body displays once for each pass.
- 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. - 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.
- Write the last number you want, and check that counting from
startby the step lands on it; if it does not, change the start or the step. Then setstoppast it, no more than one step beyond it: above it when counting up, below it when counting down. For a count up by 1,stopis the last number plus 1. Inrange(10, 0, -3)the last number is 1, and the stop 0 lies below it, within one step of 3. - Check the count: for a step of 1 and a
stopabovestart,range(start, stop)givesstopminusstartnumbers. - Write out the numbers the range gives, or note that it gives none, and compare them with what you wanted.
- Write each name the condition uses, with its value before the loop.
- Test the condition with those values. If it is false, skip to the first line after the body.
- If it is true, run the body's lines in order and write each name's new value.
- 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 thebreakof this unit's last lesson, the loop will not end on its own. - Go back to the test with the new values, and repeat until a test is false or something ends the loop sooner.
- Decide what to keep: a total, a count or the biggest value.
- 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 + stepsreads the name before it changes it, so the name needs a value first. - 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
iffinds a bigger value. - After the loop, use the result: display it, or, when the count is above 0, divide the total by the count for an average.
- Trace two passes by hand and check that the value after each pass builds on the one before.
- Above the loop, set any name that the program reads after the loop and that only a match changes, such as
found = False. - Write the test that marks a match, and put it in an
ifinside the body. - Inside that
if, do what the match needs, such as settingfound = True, and then writebreak. - Trace the passes until the test is true. At the
break, jump to the first line after the loop. - 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. Awhile True:loop that reads input and meets no match keeps reading; when the input runs out,input()stops the program with an EOFError.
Traps
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.
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.
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.
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.
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.
Lists and dictionaries
- Build an ordered list
- Update an item by index
- Look up a key
- Count repeated labels
- Choose a list or dictionary for a roster
The unit at a glance
Rules
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.
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.
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.
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.
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.
Recipes
- Write the items in order between square brackets, separated by commas.
- Number the items from 0 under the list as you trace it.
- 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. - To read an item, use its number in square brackets after the list's name. Use -1 for the last item.
- To work through every item, write a for loop over the list.
- Write the list with each index under its item.
- Before
name[i] = value, check that indexinames an item: for a list of n items, from 0 up to n - 1, or from -1 back to -n counting from the end. - For
name[i] = value, cross out the item at indexiand write the new value there. - For
name.append(value), write the value after the last item and add 1 to the length. - Print the list to see its items after the changes, and print
len()of it to see how many items it holds.
- Write each key with its value, in pairs, as the dictionary is built.
- For
d[k] = v, replace the value ifkis already a key; otherwise add the new pair at the end, since the keys keep the order they were added in. - For
d[k], find the key and read its value; if the key is missing, the program stops with a KeyError. - For
k in d, answerTruewhenkis one of the keys, andFalseotherwise.
- Set
counts = {}above the loop. - Loop over the labels with a for loop.
- Inside the loop, test
if label in counts:. - When it is true, write
counts[label] += 1; otherwise writecounts[label] = 1, which stores the new key. - After the loop, read a count with
counts[label]or print the whole dictionary.
- Write the questions the program must answer.
- If a question asks by position, such as first or next, keep a list.
- If a question asks by a name or code, keep a dictionary with that name as the key.
- Check the keys: each key holds one value only.
- Use both when the program needs both kinds of question.
Traps
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.
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.
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.
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.
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.
Functions
- Give a repeated task a name
- Pass an argument
- Return a result
- Trace a local name
- Compose two small functions
The unit at a glance
Rules
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.
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.
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.
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.
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.
Recipes
- Find the lines that the program needs in more than one place.
- Write
def, a name that says what the lines do, an empty pair of parentheses and a colon. - Put the lines under the
defline and indent them one more level, four spaces, keeping any deeper indentation they already have. - Leave the indented block, and write the function's name with parentheses at each place where the lines should run.
- Trace the program: skip the body at the
defline, and run the body at each call.
- Find the value in the body that should change from call to call.
- Give that value a name and write the name inside the parentheses of the
defline. For two values, write two names with a comma between them. - Use the names in the body where the values were.
- In each call, write the values inside the parentheses in the same order as the names.
- Trace a call by writing each parameter with the argument it received, then running the body with those values.
- Decide what value the rest of the program needs from the function.
- Write
returnfollowed 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. - At the call, do something with the value: give it a name, print it or use it in an expression.
- Trace a call by replacing it with the value it returns, then finishing the line the call was in.
- If a function should only display something, leave
returnout and call it on a line of its own.
- Draw two columns for names: one for the file's global names and one for the call's local names.
- At a call, start a fresh local column and write each parameter in it with the argument it received.
- 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. - 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.
- At a return line, work out the value to give back while the local column is still there.
- 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.
- Write the task as a list of small jobs, each one taking some values and giving one value back.
- Write one function for each job, with a parameter for each value it takes. Return its result.
- Test each function that calls no other function alone, with a few arguments, including any boundary value. Compare with results worked out by hand.
- 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.
- 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.
Traps
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.
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.
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.
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.
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.