Students tidy typed text with strip() and lower(), cut it into words with split(), pick words by place, and see why text must be tidied before it is compared. It is the first part of a text adventure.
Load these into Waypoints Prepare: choose Load URL and paste the copied address, or download the file and import it. In Prepare, the worksheet's Teacher edition shows the answers; the student copy hides them.
Predict and Run 10 min · Investigate 15 min · Modify 10 min · Make 10 min
Read the unit primer first. Text has its own commands, called with a dot: command.strip() removes spaces at both ends, .lower() and .upper() change capitals, and .split() gives a list of words. Each gives back new text; the original is unchanged unless you store the result (command = command.strip()). They can be chained: input("> ").strip().lower(). The bug task is the reason they matter: "Yes" == "yes" is False. in checks whether something is in a list.
Seeing why Yes and yes differ, and what split() gives back. Have them print the tidied text and the list of words before they fix the comparison.
| What you will see | A question to ask | The fix |
|---|---|---|
| The program ignores a command that looks right. | Was the text tidied before it was compared? | Compare the tidied text: command.strip().lower() == "quit". |
| IndexError: list index out of range. | How many words did split() give? Is there a words[1]? | Check len(words) before using words[1]. |
| The text did not change after strip() or lower(). | Was the result stored? | command = command.lower(): the method gives back new text. |
One possible solution for each task. Other correct programs are fine.
command = input("What do you do? ")
command = command.strip().lower()
words = command.split()
if command == "quit":
print("Goodbye!")
elif len(words) == 2:
print("Verb: " + words[0])
print("Thing: " + words[1])
else:
print("Try two words, such as: go north")
command = input("What do you do? ")
command = command.strip().lower()
words = command.split()
if len(words) == 2:
if words[0] in ["go", "take", "look"]:
print("Verb: " + words[0])
print("Thing: " + words[1])
else:
print("I don't understand " + words[0] + ".")
else:
print("Try two words, such as: go north")
name = input("What is your full name? ")
words = name.strip().split()
initials = ""
for word in words:
initials = initials + word[0].upper()
print("Initials: " + initials)
print("In capitals: " + name.strip().upper())
Stretch: Accept short commands too, such as n for go north, by checking a list of short forms.
Support: Give students the line that splits the name, and ask them to build the initials with a loop.
What does " Hello World ".strip().lower().split() give?
["hello", "world"]: spaces off the ends, small letters, then cut into words.
Next lesson keeps an inventory in a list (append, remove, in). The parser from this lesson comes back in the text adventure.