Up Next: Functions and Data

Look back at what Module 1 taught you, put all of it to work in a quiz game of your own, and get a first look at the functions, lists and dictionaries that Module 2 teaches.

Novice · Python · Updated

By

After this lesson you can

  • Describe what functions, lists and dictionaries will let your programs do

Key takeaways

  • After Module 1 you can store values, ask for input, make decisions and repeat work. That's enough to write a game a friend can play in the terminal.
  • A quiz game uses all of it, an input() and an if for each question, a running score, and a while loop that asks to play again.
  • Module 2's functions let you write a job once and use it everywhere, so five questions don't need five copies of the same lines.
  • Module 2's lists, tuples and dictionaries hold many values in one variable, such as a family's ages or a menu's prices.

At the start of this module, your first program printed one line of text. Look at what you can write now: programs that remember values, do the math, ask questions, make decisions and repeat work. Those are the same building blocks every program on your phone is made of.

This lesson looks back at what you can do, shows you how to put all of it into a game you can build on your own, and gives you a first look at Module 2, where your programs start packaging their work and holding whole collections of data.

What you can do now

After Module 1, you can:

  • run Python from VS Code's terminal, try a line in the REPL, and read a traceback from its last line up;
  • get exercise code with Git and hand in your work;
  • keep values in variables: whole numbers, decimals, text, and True or False;
  • calculate with + - * / // % **, build text with f-strings, and turn typed answers into numbers with int() and float();
  • make decisions with if, elif and else, joined with and, or and not;
  • repeat work with while and for loops, counting with range().

Here's a small program that uses most of it at once. It works out when a Splash Valley season pass beats buying day tickets:

pass_price = 95
day_price = 30
for visits in range(1, 6):
    tickets = visits * day_price
    if tickets > pass_price:
        choice = "the season pass"
    else:
        choice = "day tickets"
    print(f"{visits} x ${day_price} = ${tickets}: buy {choice}")
1 x $30 = $30: buy day tickets
2 x $30 = $60: buy day tickets
3 x $30 = $90: buy day tickets
4 x $30 = $120: buy the season pass
5 x $30 = $150: buy the season pass

When you started this module, a page of code like that might have looked like a foreign language. Now you can read every line of it.

Put it all together: a quiz game

Here's a way to prove it to yourself: build a quiz game a friend can play in the terminal. Pick five questions about something you know well (a sport, a TV show, your hometown), and make a file of your own, quiz.py, in your course folder. The game needs everything this module taught:

  • each question asked with input(), and the answer tidied with .strip().lower(), so For, for and FOR all count;
  • an if that says whether the answer is right, and adds 1 to a running score with +=;
  • a closing line that depends on the score, with if, elif and else: a different line for 5, for 3 or 4, and for anything less;
  • a while loop around the whole game that asks Play again? and stops when the answer isn't yes.

Here's the heart of it, one question:

score = 0
answer = input("Which loop counts with range()? ").strip().lower()
if answer == "for":
    print("Right!")
    score += 1
else:
    print("Not yet: it's the for loop.")
print("Score:", score)

A run where the player types For:

Which loop counts with range()? For
Right!
Score: 1

For a stretch, give the player three lives: each wrong answer takes one away, and the game ends when they run out.

Where it gets repetitive

Write all five questions and you'll notice something: each one is the same six lines with different words. If you decide to accept Yes as well as yes, or change how the score is counted, you change it five times, and missing one is a common slip.

The data has the same problem. Every variable you've made holds one value: one age, one price, one answer. A family of five at the ticket booth needs five variables, age_1 to age_5, and a for loop can't go through them, because they're five separate names. A real park sells thousands of tickets a day.

What Module 2 unlocks

Module 2 fixes both:

  • Functions let you write a job once, give it a name, and run it whenever you need it, with different values each time. One function asks any question and checks any answer; five calls ask five questions. The chapter's example is Stride, a step-counter app.
  • Lists and tuples hold many values in order, in one variable: [35, 8, 2] is a family's ages, and a for loop goes through them one by one.
  • Dictionaries and sets look values up by name, such as a menu's price for "popcorn", and keep collections without duplicates.

Here's a taste, with the ticket prices from this module:

def ticket_price(age):
    if age < 3:
        return 0
    elif age <= 12:
        return 18
    elif age <= 64:
        return 30
    return 20


family_ages = [35, 8, 2]
total = 0
for age in family_ages:
    total += ticket_price(age)
print("Family total:", total)
Family total: 48

The pricing rule lives in one place, ticket_price, and the family can be any size. You don't need to understand every line yet: that's what Module 2 is for.

Check yourself

2 questions to try on the lesson page.

So what

Module 1 gave you the building blocks of every program; Module 2 shows you how to package them in functions and point them at real collections of data.

Key terms

Related