← Teacher guides

Teacher guide: Console bridge: text in, text out

input(), print() and a text menu: the same logic as the turtle courses, as text in and text out. Every Python extension starts here.

Open the student course · How the ideas build

Each lesson works two ways. Students can work through the online tutorial at their own pace (it checks their answers and saves their progress in their browser), or you can teach it to the whole class from the slides, then send students into the tutorial for the Modify and Make steps.

Every lesson guide has plain-language notes, the answers to every check, a solution for every task, and slides and a worksheet for Waypoints Prepare. These guide pages are not linked from student pages, but they are not secret either: keep printed Teacher editions for answers you do not want students to find.

Course resources: Recap

Strategies for getting unstuck: Say what it should do, Test a small piece, Read the error, Trace it. A student who is stuck can try one before asking for a hint. The optional course How you learn best introduces them, and a few lesson decks have a short teach, show or nudge slide for one. (Each lesson page links to the cards from its first hint.)

Whole-course cheat sheet: Open to print (every command, grouped by unit: a handout for the final challenge)

Text in, text out

Show text, ask a question, store the answer and join numbers onto text.

Text in, text out in 5 minutes (read before teaching this unit)

The idea in plain words

A console program works with text instead of pictures. It shows a line, waits for someone to type an answer, and replies. Three pieces do almost all of it:

  • print("...") shows a line of text. Text goes in quotes, and the quotes are not shown.
  • + joins pieces of text into one: "Hello, " + name. It adds nothing, so a space only appears where it is inside the quotes.
  • input("question") shows the question, waits, and gives back what was typed. Store it with name = input(...).

A number cannot be joined onto text: "Score: " + 5 is an error. str(5) makes a text copy that can be joined.

Why programmers use them

  • Every app shows and asks. Forms, chat windows and ticket machines are the same idea with a nicer screen.
  • Messages are built from pieces. A greeting, a name and a count are joined into the line a person reads.
  • It is the bridge. The turtle courses' ideas (variables, decisions, loops, functions) carry straight over; only the screen changes.

An everyday picture, and where it breaks

A console program is a person at a counter: they say something, listen, and reply.

Where it breaks: the person at the counter hears a whole sentence. The program only holds what it was told to store, so an answer that is not stored in a name is gone.

Try it yourself (5 minutes)

  1. Run name = input("Name? ") then print("Hi " + name). Click the line in the console, type, and press Enter.
  2. Take the space out of the quotes in "Hi " and run it again. Where did the space come from?
  3. Try print("Score: " + 5) and read the message. Then fix it with str(5).

Questions students ask

  • Why does the console look different from the turtle playground? Programs that do not use the turtle get a console instead of a drawing. If a program imports turtle, the drawing comes back.
  • Why quotes? Without quotes Python looks for a name. With quotes it uses the text itself.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Numbers from text

Turn typed text into numbers, and check it first so a typo does not crash the program.

Numbers from text in 5 minutes (read before teaching this unit)

The idea in plain words

What input() gives back is always text, even when someone types digits. "5" + "5" is "55". To calculate, turn the text into a number with int("5").

int("twelve") stops the program with an error, so a careful program checks first. text.isdigit() asks the text whether every character is a digit and gives back True or False. The dot means "ask this text". An if uses the answer: convert inside the if, and reply politely in the else.

Why programmers use them

  • What people type is not what you expect. Checking input before using it (validation) is one of the most important habits in programming.
  • Real apps do this on every box. A form that says "Please enter a valid quantity" asked a question like isdigit() first.
  • A crash is a bad reply. The else turns it into a helpful one.

An everyday picture, and where it breaks

A door with a lock that asks "is this a key?" before turning.

Where it breaks: isdigit() only checks the shape of the text. 0 is all digits, so it passes even when 0 makes no sense. Checking that a number is sensible is a second question.

Try it yourself (5 minutes)

  1. Run a = input("A? "), b = input("B? "), print(a + b) with 5 and 5. Then wrap each input in int(...) and run again.
  2. Type twelve into the int() version and read the error.
  3. Add an if text.isdigit(): check around it and run it again with twelve.

Questions students ask

  • Can I type a decimal like 2.5? isdigit() says no (the dot is not a digit) and int() cannot read it. float() can, but this course sticks to whole numbers.
  • Why not just use try and except? That is a good second way, and it comes later. Checking first shows the idea in the simplest form.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Keep asking

Repeat with while, keep a running total, and read a whole guessing game.

Keep asking in 5 minutes (read before teaching this unit)

The idea in plain words

A while loop repeats for as long as a question is true: while guess != secret: keeps asking until the guess is right. It asks the question before every lap, so something inside the loop must change the answer, or the loop runs for ever (the playground's Stop button ends it).

+= adds to a variable: total += 5 is short for total = total + 5. Set the total to 0 once, before the loop, and it builds up as the loop goes.

Why programmers use them

  • You often cannot know how many times. A game, a PIN pad or a till keeps going until something happens.
  • A running total is everywhere. Scores, steps and shopping baskets all add as they go.
  • Longer programs are readable in parts. A guessing game is a set-up, a loop, a check and a count.

An everyday picture, and where it breaks

A while loop is "keep stirring while the sauce is lumpy". The cook checks before each stir, and stops when the answer changes.

Where it breaks: if nothing changes the sauce (you forget to stir), the cook checks for ever. In code, a line that asks again must be inside the loop, or the condition never changes.

Try it yourself (5 minutes)

  1. Run the guess-the-number game and count how many guesses you need. Halving the range each time always wins in five for 1 to 20.
  2. Move tries += 1 out of the loop (dedent it) and see what the program says.
  3. Change total = 0 to be inside the loop in the running-total program. What happens?

Questions students ask

  • for or while? for when you know how many times (four sides of a square); while when you are waiting for something to happen (the right guess).
  • What if it never stops? Press Stop. Then look for the line that should change the condition.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Menus and testing

A menu that keeps showing, and test cases written as a table.

Menus and testing in 5 minutes (read before teaching this unit)

The idea in plain words

A menu is while True:, a loop whose question is always yes, with break as the way out. Each lap shows the choices, asks for one, and runs one branch of an if / elif, with else for anything else. break leaves the whole loop, and the program carries on after it.

A test case is an input and the output you expect, written down before running. If the menu's replies come from a function, each test is one line: print(reply("9") == "Please choose 1 or 2.") shows True or False. A good list of tests includes the wrong inputs.

Why programmers use them

  • Menus are everywhere. ATMs, settings screens and text adventures are a loop, a decision and a way out.
  • Tests catch what you did not think of. Writing the expected output first stops you from deciding a wrong answer looks fine.
  • Functions make code testable. A function can be called with any input, with no typing.

An everyday picture, and where it breaks

A café counter: ask what they want, add it to the order, ask again, until they say that is all.

Where it breaks: a person at the counter knows when to stop. A program only stops when a line says so, so a menu with no break is a menu that never ends.

Try it yourself (5 minutes)

  1. In the till, type a few choices, then something silly, then pay. Watch which branch runs each time.
  2. Remove the break line, run it, and press Stop. What does that tell you?
  3. Write three test cases for the till (what to type, what it should reply) and run them.

Questions students ask

  • Is while True a mistake? Not when there is a break. It reads as "keep going until I say stop".
  • Why test with a function and not by typing? Typing the same choices every time is slow and easy to get wrong. A test line runs in a blink.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Console challenge

Build a console app with a menu, a checked number and a total.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Open projects

Self-paced briefs students can pick up (after the lesson named on each, where one is named). Students tick their own milestones and claim a badge; the page lights the skills their code uses. Badges stay in the student's browser: ask them to press Show your teacher. Open the projects page

A quiz game (after console-guess; input(), textinput(), numinput(), a list ([1, 2]), for item in a list, change a variable from itself (x = x + 1, +=))

Write a quiz about something you know well. It asks every question in turn, says whether each answer was right, and finishes with a score.

Milestones:

  • At least three questions, each with its own right answer.
    1. Keep each question and its answer together as a small list, inside one big list.
    2. In each small list, item[0] is the question and item[1] is the answer.
    Students can earn this piece (reveal on): questions = [
    ["What is the capital of Australia? ", "canberra"],
    ["How many legs does a spider have? ", "8"],
    ["What colour do you get from blue and yellow? ", "green"],
    ]
  • One loop asks them all, whatever the number of questions.
    1. for item in questions runs the same code once for each question.
    2. Ask with input(item[0]) and keep what they type in a variable.
    Students can earn this piece (reveal on): for item in questions:
    answer = input(item[0]).lower()
  • The program says whether each answer was right, and ends with the score.
    1. Start score at 0 before the loop, not inside it.
    2. Inside the loop, if the answer matches item[1], add 1 to score.
    3. After the loop, print the score joined to text, using str().
    Students can earn this piece (reveal on): if answer == item[1]:
    print("Correct!")
    score = score + 1
    else:
    print("Not quite. It was " + item[1] + ".")

Builds on the guessing game (a running count) and Lists (one loop over them all). Each question is a small list of a question and its answer, so item[0] and item[1] are the recipe here; students do not need to write them from scratch. The picture shows one run with a wrong answer. A good conversation: where does the score start, and what happens if it starts inside the loop?

One possible solution
questions = [
    ["What is the capital of Australia? ", "canberra"],
    ["How many legs does a spider have? ", "8"],
    ["What colour do you get from blue and yellow? ", "green"],
]

score = 0
for item in questions:
    answer = input(item[0]).lower()
    if answer == item[1]:
        print("Correct!")
        score = score + 1
    else:
        print("Not quite. It was " + item[1] + ".")

print("You scored " + str(score) + " out of " + str(len(questions)) + ".")
A fortune teller (after console-menu; while, break, a list ([1, 2]), the random module)

Build a fortune teller. It keeps asking for a question, answers each one with a reply picked at random, and stops when you type quit.

Milestones:

  • At least five replies, kept in a list.
    1. A list is square brackets with commas between the items, such as ["a", "b"].
    2. Write replies that make sense whatever the question is.
    Students can earn this piece (reveal on): replies = ["Yes, definitely.", "Ask again later.", "Not a chance.", "It looks good.", "Hard to say."]
  • It keeps asking until you type quit.
    1. while True keeps going until something tells it to stop.
    2. Inside it, check whether they typed quit before you reply, and use break to leave.
    Students can earn this piece (reveal on): while True:
    question = input("Ask a question: ")
    if question == "quit":
    break
  • Each answer is picked at random from the list.
    1. Put import random at the top of the program.
    2. random.choice(a_list) gives back one item from the list, picked at random.
    Students can earn this piece (reveal on): print(random.choice(replies))

The menu loop with break from Menu with break, with a list of replies in place of the menu. random.choice is a recipe here (Catch the turtle taught import random); students who want to explain it can use random.randint on an index instead. The loop's exit is the point: ask where quit has to be checked, before or after the reply.

One possible solution
import random

replies = ["Yes, definitely.", "Ask again later.", "Not a chance.", "It looks good.", "Hard to say."]

print("The fortune teller is ready. Type quit to leave.")
while True:
    question = input("Ask a question: ")
    if question == "quit":
        break
    print(random.choice(replies))
print("Goodbye!")