Python Mad Libs
Image by Jenna on Flickr
Recreate the classic game in this simple Python tutorial. What whimsical stories will you write?
“MadLibs” is a game where you write a story with missing words, then ask friends or family members to fill in the blanks. Since they don’t know what your story’s about, the result is often wonderful and silly!
Traditional MadLibs are done with paper and ink. But now that we’re in the digital age, we can recreate the game with some simple Python code, and reuse each MadLib over and over.
AN EXAMPLE MADLIB
To get you inspired, here’s a quick little story:
It was pizza day at school, and Jamie was super excited for lunch. But when she went outside to eat, a bird stole her pizza! Jamie chased the bird all over school. She climbed, jumped, and ran through the playground. Then she tripped on her shoelace and the bird escaped! Luckily, Jamie’s friends were willing to share their pizza with her.
On its own, the story isn’t super exciting. But let’s see what happens when we convert it into a MadLibs game:
It was ___(FOOD)___ day at school, and ___(NAME)___ was super ___(ADJECTIVE)___ for lunch. But when she went outside to eat, a ___(NOUN)___ stole her ___(FOOD)___! ___(NAME)___ chased the ___(NOUN)___ all over school. She ___(VERB1)___, ___(VERB2)___, and ___(VERB3)___ through the playground. Then she tripped on her ___(NOUN)___ and the ___(NOUN)___ escaped! Luckily, ___(NAME)___’s friends were willing to share their ___(FOOD)___ with her.
Now there’s a lot more potential for shenanigans!
Open up your browser and navigate over to www.repl.it. Click the blue ‘+ new repl’ button in the top left corner.
Select ‘Python’ from the Language Menu and hit ‘create repl’.
Time to write your story! Make it as short or as long as you like. You can either write the story normally and then blank out keywords, or just jump straight to the MadLibs version. If you’re lacking inspiration, remember that cats, dinosaurs, space exploration, and magic portals always make good story subjects!
To make sure our program treats the story as text, and not code, we need to surround it with quotation marks. Then we can store it in a variable called ‘story’:
Next, we cut out all the ‘blank spaces’ and replace them with variables. Words that are repeated – like ‘Jamie’ or ‘pizza’ – use the same variable, but otherwise each variable name must be unique. Using descriptive names (like ‘noun1’, or ‘name2’, or ‘pizza’) will help you remember what each one represents. The variables are placed into the text like so:
"It was " + food + " day at school, and "
This is the trickiest part! You need to make sure that you have a ‘+’ sign before and behind each variable. You also need to make sure that each snippet of story starts and ends with quotation marks. If you’re missing a quotation mark, the colour of your text will be off, like so:
Instead of like so:
While simple, stringing together text and variables isn’t always easy! Here’s a ticklish detail: what if you have dialogue in your story, and you need to use quotation marks? If you just write the quotes normally, then you throw off the delicate balance between text and code.
The solution is to put a backslash (\) in front of each “text” quotation mark, to separate them from “code” quotation marks. We call this “escaping” a character. Don’t worry – the backslash won’t appear when you actually display the text.
name + " said \"Hi! My name is " + name + ".\""
PSST: a forward slash (/) is not quite the same as a backslash! (\)
PSST PSST: if this feels too confusing, you can use single quotes for your dialogue!
In Python, we can use the “input” function to prompt a player for information. The text inside the function’s brackets is displayed in the console, where the user types their answer.
food = input("Enter a type of food: ")
To get all the necessary words for your MadLib, we need to add a similar line for every variable. In the code editor, these prompts go above the story section.
Finally, we end our program by displaying the finished story with the “print” function.
FULL CODE LISTING
food = input("Enter a type of food: ") jamie = input("Enter a girl's name: ") adj1 = input("Enter an adjective: ") bird = input("Enter a noun: ") verb1 = input("Enter a verb in the past tense: ") verb2 = input("Enter another verb in the past tense: ") verb3 = input("Enter a third verb in the past tense: ") noun1 = input("Enter a noun: ") story = "It was " + food + " day at school, and " + jamie + " was super " + adj1 + " for lunch. But when she went outside to eat, a " + bird + " stole her " + food + "! " + jamie + " chased the " + bird + " all over school. She " + verb1 + ", " + verb2 + ", and " + verb3 + " through the playground. Then she tripped on her " + noun1 + " and the " + bird + " escaped! Luckily, " + jamie + "'s friends were willing to share their " + food + " with her." print(story)
TIME TO PLAY!
Click the green ‘run’ button near the top of the screen. You should see your first prompt appear in the right-hand console. If so – great! Gather up friends and family, and have them answer each prompt until the story is finished and the delightful result is displayed onscreen.
If you get some sort of ‘SyntaxError’ message, double check that you’ve added all the necessary quotation marks and ‘+’ signs.
Another common error is misspelling variable names (NameError). This one’s a little trickier, because you won’t get an error message until you’re deep in the code:
If it feels like a lot to take in, start with simple sentences that have one or two variables. You can always work your way up to longer, wackier, and more complex stories once you’ve mastered the basics.
Have fun, and happy hacking!
How to make your own MadLibs
Python Escape Characters
Python Mad Libs
Build a simple mad lib
Mad Libs Generator
Also In The February 2020 Issue
Can you figure out how to divide up coconuts between a group of sailors and a monkey? This puzzle mixes math and coding. Plus you can go online to try the code yourself!
Recreate the classic game in this simple Python tutorial. What whimsical stories can you write?
If you like ships, then you’ll love this easy-to-use website that keeps track of seafaring vessels around the world. Bonus: it helps prevent maritime collisions!
Ready for some good old-fashioned winter fun? In this article, build a digital snowman with Sketchup.
A fun, silly way to share your coding trials and triumphs with friends — because everything is better with kittens!
Should you learn Python, Scratch, Java, Assembly? If you’re feeling overwhelmed by too many options, this article is here to help.
Illustrating computational concepts like decomposition and algorithms with simple, hands-on, and occasionally messy activities.
How do street lights know when to turn on? And what’s in store for the street lights of the future?
In the old days, before video game systems had cameras and sensors, programmers had to get creative.
Six women were hired to use their math skills to program the ENIAC computer. They called themselves The First Programmers Club.
Learn about the key software that keeps your computer safe from viruses.
Programs are constantly being patched and improved. How do we keep track of all this new code?
Dive into the nitty-gritty details of binary numbers: how they work, why they’re used, and where they come from.
Binary might be the language of the computer, but we humans can use it to decode secret messages.
An easy way to code your own 3D graphics online. Dive into the world of pixels, triangles, textures, and colours!
Learn about the smallest, simplest computers and where they’re still used today.
Why Smalltalk is such a unique language, and how it evolved into modern variants like Scratch, Squeak, and Pharo.
Interesting stories about science and technology for February 2020.
Links from the bottom of all the February 2020 articles, collected in one place for you to print, share, or bookmark.