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
1.1 Run your first Python program
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
- 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.
Worked example
Run the saved file
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
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
The rule
Use addition for two integers and joining for two strings.
Check for quote marks before deciding which operation this example uses.
How
- 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.
Worked example
Predict both lines
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
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
- 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.
Worked example
Trace boxes and spare
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
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
- 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.
Worked example
One reply for a badge and a count
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
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
- 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.
Worked example
Find the missing letter
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
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
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
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
2.1 Choose an arithmetic operator
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
- 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.
Worked example
Ribbon for four display frames
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
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
- 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.
Worked example
Count the pieces in four kits
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
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
- 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.
Worked example
Pack 38 postcards
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
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
- 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.
Worked example
Read the shelf tag
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
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
- 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.
Worked example
Fill the Oak shelf card
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
3.1 Ask a true-or-false question
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
- 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.
- Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Comparisons
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: int
- Python Software Foundation, Python 3.13 Language Reference, 6.10 Comparisons
Worked example
Ask three questions about a boat
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
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.
- Python Software Foundation, Python 3.13 Tutorial, 3.1.1 Numbers
- Python Software Foundation, Python 3.13 Language Reference, 6.10 Comparisons
- Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Comparisons
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: int
- Python Software Foundation, Python 3.13 Tutorial, 8.1 Syntax Errors
3.2 Choose a branch
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
- 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.
Worked example
Type 30 for a bag over the limit
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
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
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.
- Python Software Foundation, Python 3.13 Language Reference, 2.1.8 Indentation
- Python Software Foundation, Python 3.13 Language Reference, 8 Compound statements and 8.1 The if statement
- Python Software Foundation, Python 3.13 Tutorial, 8.1 Syntax Errors
- Python Software Foundation, Python 3.13 Tutorial, 4.10 Intermezzo: Coding Style
- Python Software Foundation, Python 3.13 Library Reference, Built-in Exceptions: IndentationError
3.3 Handle a boundary value
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
- 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.
Worked example
Type 2, the first boundary value
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
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
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
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
- 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.
Worked example
Tall enough, with a ticket
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
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
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).
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: int
- Python Software Foundation, Python 3.13 Language Reference, 6.11 Boolean operations
- Python Software Foundation, Python 3.13 Language Reference, 8 Compound statements and 8.1 The if statement
- Python Software Foundation, Python 3.13 Language Reference, 6.17 Operator precedence
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.
- Python Software Foundation, Python 3.13 Language Reference, 6.11 Boolean operations
- Python Software Foundation, Python 3.13 Language Reference, 6.10 Comparisons
- Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Truth Value Testing
- Python Software Foundation, Python 3.13 Language Reference, 6.17 Operator precedence
3.5 Trace a ticket rule
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
- 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.
Worked example
A member aged 16
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
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
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
4.1 Read a for loop
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
- 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.
Worked example
Display each character of a string
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
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
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
- 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.
Worked example
Count from 1 to 5
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
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
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
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
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
- 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.
Worked example
Count down to Go
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
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
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
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
- 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.
Worked example
Add up four days of steps
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
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
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.
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: int
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Tutorial, 3.2 First Steps Towards Programming
- Python Software Foundation, Python 3.13 Tutorial, 3.1.1 Numbers
- Python Software Foundation, Python 3.13 Language Reference, 8.1 The if statement
- Python Software Foundation, Python 3.13 Language Reference, 7.2.1 Augmented assignment statements
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
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
- 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.
- Python Software Foundation, Python 3.13 Language Reference, 8.1 The if statement
- Python Software Foundation, Python 3.13 Language Reference, 7.9 The break statement
- Python Software Foundation, Python 3.13 Language Reference, 8.3 The for statement
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
Worked example
Stop at the first space
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
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
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.
- Python Software Foundation, Python 3.13 Tutorial, 4.4 break and continue Statements
- Python Software Foundation, Python 3.13 Language Reference, 8.2 The while statement
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Language Reference, 7.9 The break statement
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
5.1 Build an ordered list
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
- 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.
Worked example
Read a list by index and by loop
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
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
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
- 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.
Worked example
Replace an item and add one
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
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
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
- 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.
Worked example
Store, replace and read by key
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
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
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
- 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.
- Python Software Foundation, Python 3.13 Tutorial, 5.5 Dictionaries
- Python Software Foundation, Python 3.13 Tutorial, 4.2 for Statements
- Python Software Foundation, Python 3.13 Language Reference, 8.1 The if statement
- Python Software Foundation, Python 3.13 Language Reference, 7.2.1 Augmented assignment statements
Worked example
Count five votes
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.
- Python Software Foundation, Python 3.13 Library Reference, Built-in Exceptions: KeyError
- Python Software Foundation, Python 3.13 Language Reference, 7.2.1 Augmented assignment statements
- Python Software Foundation, Python 3.13 Language Reference, 8.1 The if statement
- Python Software Foundation, Python 3.13 Tutorial, 5.5 Dictionaries
- Python Software Foundation, Python 3.13 Tutorial, 4.2 for Statements
5.5 Choose a list or dictionary for a roster
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
- 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.
Worked example
Keep a seating list and a room dictionary
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
6.1 Give a repeated task a name
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
- 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.
Worked example
Call one function twice
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
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
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
- 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.
Worked example
Greet two guests with one function
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
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
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
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
- 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.
Worked example
Use a returned price twice
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
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
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
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
- 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.
Worked example
Assign a name that also exists outside
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
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
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
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
- 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.
Worked example
Join three functions into a receipt
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
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.