Python 13 · Turn typed messages into commands

Python lesson 13 of 50 · Early intermediate · About 35 minutes

The control desk comes online. Teach it to accept mixed-case commands and handle blank input safely.

Pip sits at the crossing of moon tracks near the lit Workshop and Greenhouse, with a beacon on a far ridge.

Mission Separate a player’s typed message into a command and an optional argument.

Get ready

Read this as the next checkpoint in Pip’s mission. You can also start with the complete program below.

Open the browser Python editor (opens in a new tab), replace its example with the complete checkpoint below and choose Run. Use Python 3.10 or newer.

Clean the line. Trim spaces and convert to lowercase.. → Split once. Separate the action from its argument.. → Choose a response. Run the matching command or keep listening..
Clean the line → Split once → Choose a response

Understand the Python in this lesson

Read the explanations, then follow the worked example before changing the code.

Tidy the text before checking it

text.strip().lower().split(maxsplit=1) is a chain. Each method uses the result of the last one. strip() removes spaces at the ends, lower() changes capitals to lowercase, and split() makes a list of pieces. The named option maxsplit=1 allows at most one split, leaving any extra words together as the argument.

Read positions in the list

The first list position is words[0]. Python starts counting at zero. words[1] is the second position and is only read when len(words) == 2. The expression value if condition else other picks one of two values. Here it gives a one-word command an empty argument.

Return two answers together

if not words spots an empty list before reading the first position. return "", "" gives back two empty strings. In both return paths Python bundles the two values as a pair called a tuple. command, argument = read_command(raw) unpacks that pair into two names.

Keep reading until you stop

while True keeps the radio listening. try runs input(), and except EOFError handles the signal that the input stream has ended. break leaves the loop. The empty cargo string becomes "empty" through or, and the f before the status string lets Python fill in the expressions inside its braces.

How the pieces fit All later commands use the same rule for separating a command from its argument. When movement arrives, a line such as go north is already split into the parts the game needs.

Follow one run, step by step
  1. Type LOOK
    The command pair is ("look", ""). Why Tidying the input removes the extra spaces and capitals.
  2. Run the look branch
    Pip wakes in the Habitat. and Exits: north, east Why The game uses the same map function as Lesson 12.
  3. Type status
    Habitat | Energy: 8 | Cargo: empty Why The status format uses Pip’s current state.
  4. Type quit
    Mission paused. Why This branch prints the message and breaks out of the loop.

Predict before you run What happens if you press Enter without typing a command?

Reveal the explanation

The list is empty, so read_command() returns two empty strings before it tries words[0]. The game prints Unknown command. and asks again.

Look up Python words and symbols in the course reference

Build the checkpoint

Python skills strip and lower, split with maxsplit, Command loop.

1. Clean up the message

Try typing LOOK with a space at each end. Before the program compares the text, it uses strip() and lower(). This removes surrounding space and turns capitals into lowercase. split(maxsplit=1) splits just once so a future command can keep a longer argument, such as the name of a tool.

def read_command(text):
    words = text.strip().lower().split(maxsplit=1)
    if not words:
        return "", ""
    command = words[0]
    argument = words[1].strip() if len(words) == 2 else ""
    return command, argument

2. Handle a blank radio message

If the line contains no words, the function returns two empty strings. This keeps the return shape the same for every input. With one word, command gets that word and argument is empty. With two pieces, argument holds the rest of the message, ready for the movement command in the next lesson.

if not words:
        return "", ""
    command = words[0]
    argument = words[1].strip() if len(words) == 2 else ""
    return command, argument

3. Listen one line at a time

The loop waits at the Pip prompt, calls read_command and checks the result. Try look and status first. Typing quit reaches break. If a runner closes input instead, the EOF handler prints a short message and finishes. You can now rerun the checkpoint without an old game left waiting for input.

while True:
    try:
        raw = input("Pip > ")
    except EOFError:
        print("Radio closed.")
        break

    command, argument = read_command(raw)
    if command == "quit":
        print("Mission paused.")
        break
    elif command == "look":
        look(state)
Complete Python checkpoint · moonbase_13.py
WORLD = {
    "Habitat": {"scene": "Pip wakes in the Habitat.", "exits": {"north": "Workshop", "east": "Greenhouse"}},
    "Workshop": {"scene": "Tools click together in the Workshop.", "exits": {"south": "Habitat", "east": "Beacon"}},
    "Greenhouse": {"scene": "Leaves brush the Greenhouse window.", "exits": {"west": "Habitat", "north": "Beacon"}},
    "Beacon": {"scene": "The Beacon stands quiet.", "exits": {"west": "Workshop", "south": "Greenhouse"}},
}

state = {
    "room": "Habitat",
    "energy": 8,
    "parts": [],
    "rescued": False,
}

def look(state):
    room = state["room"]
    info = WORLD[room]
    print(info["scene"])
    print("Exits:", ", ".join(info["exits"]))

def show_status(state):
    cargo = ", ".join(state["parts"]) or "empty"
    print(f'{state["room"]} | Energy: {state["energy"]} | Cargo: {cargo}')

def read_command(text):
    words = text.strip().lower().split(maxsplit=1)
    if not words:
        return "", ""
    command = words[0]
    argument = words[1].strip() if len(words) == 2 else ""
    return command, argument

print("Moonbase Rescue")
look(state)
while True:
    try:
        raw = input("Pip > ")
    except EOFError:
        print("Radio closed.")
        break

    command, argument = read_command(raw)
    if command == "quit":
        print("Mission paused.")
        break
    elif command == "look":
        look(state)
    elif command == "status":
        show_status(state)
    else:
        print("Unknown command.")

Read the complete checkpoint line by line

Use this guide beside the checkpoint. Blank lines separate ideas. Indented lines belong to the instruction above them. Lines with brackets still open can carry on below.

Lines 1–27
Lines 1–6 WORLD = { "Habitat": {"scene": "Pip wakes in the Habitat.", "exits": {"north": "Workshop", "east": "Greenhouse"}}, "Workshop": {"scene": "Tools click together in the Workshop.", "exits": {"south": "Habitat", "east": "Beacon"}}, "Greenhouse": {"scene": "Leaves brush the Greenhouse window.", "exits": {"west": "Habitat", "north": "Beacon"}}, "Beacon": {"scene": "The Beacon stands quiet.", "exits": {"west": "Workshop", "south": "Greenhouse"}}, }
Work out the value on the right, then store it in WORLD. Each colon pairs a key with its value.
Lines 8–13 state = { "room": "Habitat", "energy": 8, "parts": [], "rescued": False, }
Work out the value on the right, then store it in state. Each colon pairs a key with its value.
Line 15 def look(state):
Define look, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 16 room = state["room"]
Work out the value on the right, then store it in room. The brackets look up a dictionary key or a position that starts at zero.
Line 17 info = WORLD[room]
Work out the value on the right, then store it in info. The brackets look up a dictionary key or a position that starts at zero.
Line 18 print(info["scene"])
Show the message or value in the output. The brackets look up a dictionary key or a position that starts at zero.
Line 19 print("Exits:", ", ".join(info["exits"]))
Show the message or value in the output. Put strings together with the text before .join separating them. The brackets look up a dictionary key or a position that starts at zero.
Line 21 def show_status(state):
Define show_status, a reusable piece of the program. Its input names are state. The indented body runs when something calls it.
Line 22 cargo = ", ".join(state["parts"]) or "empty"
Work out the value on the right, then store it in cargo. With or, the first true result can settle the check. Put strings together with the text before .join separating them. The brackets look up a dictionary key or a position that starts at zero.
Line 23 print(f'{state["room"]} | Energy: {state["energy"]} | Cargo: {cargo}')
Show the message or value in the output. Python fills the braces with values before it uses the text. The brackets look up a dictionary key or a position that starts at zero.
Line 25 def read_command(text):
Define read_command, a reusable piece of the program. Its input names are text. The indented body runs when something calls it.
Line 26 words = text.strip().lower().split(maxsplit=1)
Work out the value on the right, then store it in words. Return a copy with whitespace removed from the beginning and end. Return a lowercase copy so capital letters do not change a command. Separate the string into a list of pieces.
Line 27 if not words:
Run the indented block only if this check is true. The word not reverses which result counts as true.
Lines 28–42
Line 28 return "", ""
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 29 command = words[0]
Work out the value on the right, then store it in command. The brackets look up a dictionary key or a position that starts at zero.
Line 30 argument = words[1].strip() if len(words) == 2 else ""
Work out the value on the right, then store it in argument. Choose the first value if the condition is true, otherwise choose the value after else. Count the characters or items. Return a copy with whitespace removed from the beginning and end.
Line 31 return command, argument
Leave this function now and hand the result back to the line that called it. Commas group these values into an ordered tuple.
Line 33 print("Moonbase Rescue")
Show the message or value in the output.
Line 34 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 35 while True:
Repeat the indented work until a break, return or error ends this path.
Line 36 try:
Attempt the indented instructions. A matching except below can deal with a problem.
Line 37 raw = input("Pip > ")
Work out the value on the right, then store it in raw. Show the prompt and wait for the player to type a line. The answer starts as text.
Line 38 except EOFError:
Run this part only when the try block raises EOFError.
Line 39 print("Radio closed.")
Show the message or value in the output.
Line 40 break
Leave the nearest loop immediately and continue after it.
Line 42 command, argument = read_command(raw)
Give each returned value to the matching name, from left to right. Run read_command with the supplied inputs and come back here when it returns.
Lines 43–51
Line 43 if command == "quit":
Run the indented block only if this check is true.
Line 44 print("Mission paused.")
Show the message or value in the output.
Line 45 break
Leave the nearest loop immediately and continue after it.
Line 46 elif command == "look":
Run the indented block only if this check is true.
Line 47 look(state)
Run look with the supplied inputs and come back here when it returns.
Line 48 elif command == "status":
Run the indented block only if this check is true.
Line 49 show_status(state)
Run show_status with the supplied inputs and come back here when it returns.
Line 50 else:
Take this branch if the earlier checks for this decision were false.
Line 51 print("Unknown command.")
Show the message or value in the output.

Test the mission

  • Type an empty line and then status. The second command should still work.
  • Try a mixed-case QuIt to check normalisation.

If something goes wrong

An empty message crashes at words[0].
Return two empty strings before reading the first element of an empty list.

Mission extension

Add a help command that prints the three commands and leaves the game running.