How to Create a Mad Libs Game in Python?

Estimated read time 2 min read

To create a Mad Libs game in Python, you can use the input() function to prompt the user for different types of words, and then use string formatting to fill in the blanks in a pre-written story. Here’s an example of how to create a Mad Libs game in Python:

# define the story templates
story1 = "Once upon a time, there was a {adjective} {noun} who loved to {verb}."
story2 = "There was a {adjective} {noun} who lived in a {adjective} {place} and loved to {verb}."

# prompt the user to choose a story
print("Choose a story:")
print("1. Once upon a time...")
print("2. There was a...")
choice = input("Enter 1 or 2: ")

# prompt the user for input based on the chosen story
if choice == "1":
    adjective = input("Enter an adjective: ")
    noun = input("Enter a noun: ")
    verb = input("Enter a verb: ")
    mad_libs = story1.format(adjective=adjective, noun=noun, verb=verb)
elif choice == "2":
    adjective1 = input("Enter an adjective: ")
    noun = input("Enter a noun: ")
    adjective2 = input("Enter another adjective: ")
    place = input("Enter a place: ")
    verb = input("Enter a verb: ")
    mad_libs = story2.format(adjective=adjective1, noun=noun, adjective2=adjective2, place=place, verb=verb)
else:
    print("Invalid choice")

# print the resulting story
print(mad_libs)

In this example, we define two story templates with placeholders for the words the user will input. We then prompt the user to choose a story by entering 1 or 2.

If the user chooses story 1, we prompt them for an adjective, a noun, and a verb, and then use string formatting to fill in the blanks in story1. If the user chooses story 2, we prompt them for an adjective, a noun, another adjective, a place, and a verb, and then use string formatting to fill in the blanks in story2.

Finally, we print the resulting story. You can modify this example to include more story templates and more placeholders. You could also use random words from a word bank or a list of pre-defined words instead of user input to create the Mad Libs game.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply