Python Kitchen

Your brigade rank
Kitchen Porter
0 tickets cleared
Chef DorranRight. New starter. Get your whites on, we've got tickets coming in.
The order
your_code.pyLighting the stove…
1
Output from print() shows up here.
practice.pyLighting the stove…
1
Run your code and the output lands here.

Your progress

Progress saves on this device only. Make a backup code to keep it safe or move it to another phone or computer.

Restore a backup

Paste a backup code from another device to carry on where you left off.

Tell Kris what you think

Found a bug, got stuck on a ticket, or loved it? Kris reads every message.

Email feedback

Or send it to hello@kralnugames.com

Settings

Chef's voice, and picking which voice he uses, live in Settings on the main menu.

Start again

Wipes your cleared tickets, hints and ticket code on this device. Make a backup first if you might want it back.

The whole course on one shelf. Every dark code box has a Try it button that sends it to the practice station, so you can run it and change it.

How Python reads your code

Python runs your file from top to bottom, one line at a time, like a recipe. If a line breaks, it stops there and tells you which line.

  • Case matters. print works, Print doesn't. dish and Dish are two different variables.
  • Spaces at the start of a line matter. They show what belongs inside an if, loop or function. Use 4 spaces.
  • Comments start with #. Python skips them. Use them to leave yourself notes.
# This is a comment
print("Line one")    # comments can sit at the end too
print("Line two")

Strings (text)

Text goes in quotes, single or double. Python calls it a string.

dish = "fish pie"
print(dish.upper())          # FISH PIE
print(dish.title())          # Fish Pie
print(len(dish))             # 8 characters
print(dish[0])               # f, the first character
print(dish.replace("fish", "cottage"))
print("pie" in dish)         # True
print("  messy  ".strip())   # tidies the spaces
print("Ha" * 3)              # HaHaHa

Need a quote mark inside text? Use the other kind outside: "86'd".

f-strings

Put f before the quote and anything in { } gets filled in. You can even do maths inside.

table = 7
covers = 4
print(f"Table {table}, {covers} covers")
print(f"That's {covers * 2} bread rolls")
price = 12.5
print(f"£{price:.2f}")       # £12.50, two decimal places

Numbers and maths

SymbolDoesExample
+add3 + 2 → 5
-take away3 - 2 → 1
*times3 * 2 → 6
/divide (always a decimal)7 / 2 → 3.5
//divide, drop the remainder7 // 2 → 3
%just the remainder7 % 2 → 1
**to the power of2 ** 3 → 8

Whole numbers are int, decimals are float. Brackets go first, just like school maths.

print(round(3.14159, 2))   # 3.14
print(abs(-5))             # 5
print(max(4, 9, 2), min(4, 9, 2))

Variables

A labelled tub. = means "put this in", not "equals".

  • Letters, numbers and underscores only. No spaces: write main_course.
  • Can't start with a number: 2nd_dish breaks.
  • Give them names that say what's inside. covers beats x.
stock = 10
stock = stock - 3     # now 7
stock -= 2            # shortcut, now 5
stock += 10           # now 15
print(stock)

input() and converting

input() always gives text. Convert it before doing maths.

ToolTurns intoExample
int()whole numberint("5") → 5
float()decimalfloat("2.5") → 2.5
str()textstr(7) → "7"
type()tells you the typetype(5) → int
covers = int(input("How many covers? "))
print(covers * 2)

Comparisons and logic

WriteMeans
==is equal to (two equals signs!)
!=is not equal to
< >less than, more than
<= >=at most, at least
andboth must be true
orat least one is true
notflips True and False

Every comparison gives back True or False. These are called booleans.

temp = 4
print(temp <= 5)                  # True
print(temp > 0 and temp <= 5)     # True
print(not True)                   # False

if, elif, else

Ends with a colon. The lines underneath are indented 4 spaces. Python runs the first branch that's true, then skips the rest.

temp = 58
if temp < 50:
    print("Rare")
elif temp < 60:
    print("Medium")
else:
    print("Well done")
print("Rest the steak")   # not indented, always runs

Lists

An ordered row of things in square brackets. Positions start at 0. Negative numbers count from the end.

prep = ["onions", "carrots", "celery"]
print(prep[0], prep[-1])     # onions celery
prep.append("garlic")        # add to the end
prep.insert(0, "stock")      # add at position 0
prep.remove("celery")        # take out by name
last = prep.pop()            # take out the last one
prep.sort()                  # A to Z
print(prep, len(prep))
print(prep[0:2])             # slice: positions 0 and 1
print("onions" in prep)

for loops and range()

Repeat steps for each item. range(start, stop, step) makes numbers and stops before the stop.

for dish in ["soup", "pie"]:
    print(f"Plate the {dish}")

for n in range(1, 4):        # 1, 2, 3
    print(n)

for n in range(10, 0, -3):   # 10, 7, 4, 1
    print(n)

for i, dish in enumerate(["soup", "pie"]):
    print(i, dish)           # numbers each item

while loops

Keeps going while the condition is true. Something inside must change, or it never stops. break jumps out early. continue skips to the next round.

stock = 0
while stock < 10:
    stock += 4
    print(stock)

n = 0
while True:
    n += 1
    if n == 3:
        continue     # skip printing 3
    if n > 5:
        break        # stop completely
    print(n)

Functions

A recipe with a name. def writes it, calling it runs it. Ingredients go in the brackets (parameters). return hands a result back.

def with_vat(price):
    return price * 1.2

def greet(name, table=1):     # table has a default
    print(f"Evening {name}, table {table}")

total = with_vat(10)
print(round(total, 2))
greet("Sam")
greet("Alex", 5)

Variables made inside a function stay inside it. That's called scope.

Dictionaries

Keys matched to values, in curly brackets. Like a menu: dish → price.

menu = {"soup": 6, "pie": 12}
print(menu["soup"])           # 6
menu["burger"] = 14           # add a new dish
menu["soup"] = 7              # change a price
print(menu.get("lasagne", 0)) # 0 instead of crashing
print("pie" in menu)          # checks keys
for dish, price in menu.items():
    print(f"{dish}: £{price}")

Catching mistakes: try / except

Put risky code in try. If it fails, the except part runs instead of crashing.

answer = "four"
try:
    covers = int(answer)
    print(covers * 2)
except ValueError:
    print("That's not a number, chef")

Reading error messages

Errors aren't failure, they're the kitchen telling you what's wrong. Read the last line first, then go to the line number.

ErrorUsually means
SyntaxErrorTypo in the shape of the code: missing bracket, quote or colon.
IndentationErrorSpaces at the start of a line are wrong.
NameErrorA name Python doesn't know. Spelling, or missing quotes on text.
TypeErrorMixing types, like adding text to a number.
ValueErrorRight type, wrong value, like int("four").
IndexErrorAsking for a list position that doesn't exist.
KeyErrorAsking a dictionary for a key it doesn't have.
ZeroDivisionErrorDividing by zero.

Thinking like a programmer

  • Break it down. Write the steps in plain English as comments first, then turn each into code.
  • Run early, run often. Test after every couple of lines, not after twenty.
  • Print to investigate. Not sure what a variable holds? print(it). Pros do this all the time.
  • Read the error, then the line. The line number is the first place to look, but sometimes the real mistake is the line above.
  • Change one thing at a time. Then you know what fixed it.

Taking it to a real terminal

Once you've cleared the rail, write Python on your own computer. On Linux, Python 3 is usually already installed.

  • Open a terminal and type python3 to get an interactive prompt. Type exit() to leave.
  • Save code in a file ending .py, like kitchen.py, using any text editor.
  • Run it with python3 kitchen.py from the same folder.
  • A proper editor like VS Code adds colours, autocomplete and error underlines.