Mad Libs story generator
Mad Libs are stories with blanks. You choose the words first, without seeing the story, and the result is usually ridiculous. You'll store your words in a dictionary, drop them into story templates, and let Python pick which story to tell.
Skills you'll practise
- Strings
- Dictionaries
- Lists
- random.choice
Steps
Step 1: Collect your words
Store each word in a dictionary, with the kind of word as the key:
"animal": "otter". The starter has one blank left for you to fill.Show a hintHide the hint
Every value should be a string in quotes, and every pair needs a comma after it.
Step 2: Write a story template
Write a sentence with
{adjective},{animal}and the other keys in curly braces where the blanks go.Show a hintHide the hint
The names inside the braces must match your dictionary keys exactly, including spaces and capital letters.
Step 3: Fill in the blanks
Call
template.format(**words)to swap every{name}for its word, then print the result.Show a hintHide the hint
The
**unpacks the dictionary, soformatreceivesadjective="sparkly", animal="otter"and so on.Step 4: Catch empty words
Before printing, check whether any word is still an empty string and tell the player which ones to fill in.
Show a hintHide the hint
A list comprehension works well:
[name for name, word in words.items() if word.strip() == ""].Step 5: Add more stories
Put two or three templates in a list and use
random.choiceto pick one each time you run it.
Starter code
It already runs. The TODO comments mark where to start.
import random
# 1. Your words. Change any of them to whatever you like.
words = {
"adjective": "sparkly",
"animal": "otter",
"place": "the library",
"verb": "juggling",
"food": "", # TODO: fill this one in
}
# 2. A story template. Each {name} is a blank.
template = "Yesterday a {adjective} {animal} walked into {place}."
# 3. TODO: fill the blanks with template.format(**words) and print the story.
print(template)
Example solution
One way to finish it. Have a go first; yours doesn't need to match.
Reveal the solutionHide the solution
import random
words = {
"adjective": "sparkly",
"animal": "otter",
"place": "the library",
"verb": "juggling",
"food": "pancakes",
}
templates = [
"Yesterday a {adjective} {animal} walked into {place} and started {verb}. "
"Everyone cheered, and then they all shared some {food}.",
"Breaking news: a {adjective} {animal} has been spotted {verb} near {place}. "
"Witnesses say it smelled faintly of {food}.",
"My favourite memory is {verb} with a {adjective} {animal} in {place}, "
"eating {food} until the sun went down.",
]
missing = [name for name, word in words.items() if word.strip() == ""]
if missing:
print("Fill in these words first:", ", ".join(missing))
else:
story = random.choice(templates).format(**words)
print(story)
Stretch goal
Let a friend play: use input() to ask for each word (type the answers in the playground's input box before you press Run), so they choose words without seeing the story.