Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

community creator

How to create madlibs using Python

Kamakolanu Srivalli Savitri Kalyani

MadLibs help you to create funny little tales through its interactive templates. MadLibs come in all sorts of platforms (e.g., newspapers, puzzle books, online games), but you can take it up a notch by creating your own.


  1. Create a python file with the extension .py
  2. Enter the python code given in the preview below, or feel free to change up the template as you wish to create your own story!
  3. Run and unfold the final story!
loop = 1
while (loop < 10):
#All the questions that the program asks the user
    pnoun1 = "monkeys"
    adj1 = "cute"
    pnoun2 = "dolphins"
    pnoun3 = "snowglobes"
    adj2 = "weird"
    color = "color! pink"
    adj3 = "bald"
    noun1 = "spoon"
    pnoun4 = "cats"
    adj4 = "sweet"
    place = "New york"
#Displays the story based on the users input
    print ("\n-------------Here's Your very own Unicorn MadLib Story!-----------------------------")
    print ("Unicorns aren't like other",pnoun1,";they're ", adj1,".\nThey look like ",pnoun2,",with ",pnoun3,"for feet and a",adj2,"mane of hair.")
    print ("But unicorns are",color,"and have a",adj3,noun1,"on their heads.")
    print ("Some",pnoun4,"don't believe unicorns are",adj4,",but I believe in them!")
    print ("I would love to take my unicorn to",place)
#Loop back to "loop = 1"
    loop = loop + 1

The logic behind the code for this MadLib project

  1. Multiple string variables are declared in order to store user details.

  2. Once all the blanks are filled by the player, the control is then passed to the printing of the player’s story to read!

  3. Prior to the declaration in the code, a looping variable called loop, which is initialized to 1, is declared.

  4. A while loop is used with loop as its looping variable under which all the input() and print() statements are written.

  5. The condition for the number of iterations under while refers to the number of times the player will be able to play around and create stories.

This means that, initially, loop=1 will be incremented each time a story is printed. While this loop value stays within the condition of the while loop, the code under it will be executed that many times. Here, we have given 10 as the looping variable, so the player can keep filling in the blanks to create up to 9 stories!

However, you can change this static loop value to make it dynamic and enhance the game’s code. This loop’s value can be taken from the player themselves through an input() statement that will hold the number of times they want to play the game.

The code used for this would be:

loop=int(input("How many times do you want to play?"))


community creator


Kamakolanu Srivalli Savitri Kalyani

View all Courses

Keep Exploring