88|PYTHON – Mad Libs Help

BYU Student Author: @IWillyerd
Reviewers: @Erick_Sizilio, @Jae
Estimated Time to Solve: 20 Minutes

We provide the solution to this challenge using:

  • Python

You can use Google Collab as the Integrated Development Environment (IDE) to complete the challenge. The challenge solution uses both the Pandas library and “Random” library.

Need a program? Click here.

Overview
You have just started dating someone who loves to play Mad Libs, a word game where you input a noun, adjective, or verb to change the story at certain moments. However, you struggle to come up with appropriate words to use in the game. Fortunately, you stumbled upon an Excel sheet containing three tabs filled with adjectives, verbs, and nouns that are perfect for Mad Libs. As a result, you decide to utilize your Python skills to create a function that will randomly generate a word and aid you in improving your Mad Libs abilities.

Instructions

  1. Open the Excel sheet and access the three tabs containing the list of nouns, verbs, and adjectives
  2. Read in the tabs and create three lists – a noun list, an adjective list, and a verb list – to store the data
  3. When reading in the lists clean the inputs as necessary, make sure to account for any white space in each list item and remove it before or after storing the item in the list
    Hint
    #Read in the data from the excel as a Panda’s DataFrame then use the following code to convert to a list  
    my_list = df[‘Words’].tolist() 
    
    #One line code to clean each of the list items 
    my_list = [string.strip() for string in my_list] 
    
  4. Create a function that will return (or print) a random verb, noun, or adjective from the lists you created based on what the user specifies. Additionally, ensure the function does the following:
    • The user needs to specify which list they want a word from. Additionally, embed the input into a loop so that they will be prompted to keep trying until they type in an accepted input.
    • Your code should eliminate any white spaces so that the function works no matter how much white space is typed by the user.
    • The responses from the user should also be case insensitive.
Suggestions and Hints
#Use a while True loop to get the correct input try the following format 
    while True: 
        my_input = my_input(‘Input a number 1-3’) 
        if input in [‘1’,’2’,’3’]: 
            break 
        print('Input a number 1-3’)  

#Use the following code to make it insensitive or to deal with spaces 
my_input = my_input.strip() #Gets rid of whitespace before and after 
my_input = my_input.upper() #Makes the string all uppercase to make it case insensitive (can also use .lower()) 

Data Files

Solution

Solution Code
#Reads in Packages 
import pandas as pd 
import random 

#Reads in all the sheets as a df to create a list 
df_noun = pd.read_excel('Challenge88_Word_Lists.xlsx',sheet_name='Nouns') 
df_adj = pd.read_excel('Challenge88_Word_Lists.xlsx',sheet_name='Adjectives') 
df_verb = pd.read_excel('Challenge88_Word_Lists.xlsx',sheet_name='Verbs') 

#Converts all the dataframes into a list 
noun_list = df_noun['Words'].tolist() 
adj_list = df_adj['Words'].tolist() 
verb_list = df_verb['Words'].tolist() 

#Strips all the whitespace from each of the strings 
noun_list = [string.strip() for string in noun_list] 
adj_list = [string.strip() for string in adj_list] 
verb_list = [string.strip() for string in verb_list] 

#Creates the function that you'll call to get a random word from the list 
def mad_libs(): 
    #Creates a loop that won't break unless the user inputs the necessary word 
    while True: 
        choice = input('Select either "Noun","Adjective",or "Verb"')#Takes in user input 
        choice = choice.strip()#strips out any spaces if that was input 
        choice = choice.upper()#makes it all uppercase so that its case INSENSITIVE 
        if choice in ['NOUN','ADJECTIVE','VERB']:#compares the choice to the list of okay words that will break the loop if correct 
            break 
        print('Please input "Noun","Adjective",or "Verb"')#string that will print everytime they input the wrong response 

    #IF statements that will correctly return the word from the selected list 
    if choice == 'NOUN': 
        word = random.choice(noun_list)#random function will randomly select a word from the list 
    if choice == 'ADJECTIVE': 
        word = random.choice(adj_list) 
    if choice == 'VERB': 
        word = random.choice(verb_list) 

    print(word)#prints the random word 

#Calls the random word function 
mad_libs() 

Challenge88_Solution.txt
Solution Video: Challenge 88|PYTHON – Mad Libs Help

Fun challenge! I followed your hints and went down a very similar path in my code. I only had slight variations that come from my personal style. I had a little trouble at the end using a Userinput as my variable rather than choice. Your solution helped me understand the issue and clear it up!
Challenge

Here is my solution! I appreciated your notes you put in your solution code, it helped me understand how to use the ‘random’ method/function. Thanks!

Fun challenge! Good reminder of loop functions and the random function. My code is pretty similar to the solution minus some style things. I did use the hint to get the tolist() part which was super helpful! My images won’t attach but this is the code I used for the def function part:

list4 = [‘NOUN’,‘ADJECTIVE’,‘VERB’]
def words():
while True:
category = input(‘Type in “Noun”,“Adjective”,or “Verb”’)
category = category.strip()
category = category.upper()
if category in list4:
break
print(‘Your input is incorrect. Please try again. Type in “Noun”,“Adjective”,or “Verb”’)
if category == ‘NOUN’:
word = rd.choice(list)
if category == ‘ADJECTIVE’:
word = rd.choice(list2)
if category == ‘VERB’:
word = rd.choice(list3)
print(word)

Thanks!

Here is my solution below:

import pandas as pd
import random

excel_file_path = ‘Challenge88_Word_Lists.xlsx’
excel_file = pd.ExcelFile(excel_file_path)

sheet_names = excel_file.sheet_names
print(“Available sheets:”, sheet_names)

while True:
selected_sheet_input = input("Enter ‘Noun’, ‘Adjective’, or ‘Verb’: “).strip().title()
if selected_sheet_input in [‘Noun’, ‘Adjective’, ‘Verb’]:
sheet_mapping = {‘Noun’: ‘Nouns’, ‘Adjective’: ‘Adjectives’, ‘Verb’: ‘Verbs’}
selected_sheet = sheet_mapping[selected_sheet_input]
break
else:
print(f"Invalid input ‘{selected_sheet_input}’. Please enter a valid option.”)

selected_df = excel_file.parse(selected_sheet)

expected_column = ‘Words’
if expected_column not in selected_df.columns:
raise ValueError(f"Column ‘{expected_column}’ not found in the DataFrame.")

word_list = [str(word).strip() for word in selected_df[expected_column]]

def get_random_word(word_list):
“”"
Returns a random word from the specified list.
“”"
return random.choice(word_list)

random_word = get_random_word(word_list)
print(f"Random {expected_column}: {random_word}")

import random
from openpyxl import load_workbook

workbook = load_workbook(‘path_to_your_excel_file.xlsx’) # Replace ‘path_to_your_excel_file.xlsx’ with the actual path

noun_list = [noun.strip().upper() for noun in workbook[‘Nouns’][‘A’] if noun.value is not None]
adjective_list = [adjective.strip().upper() for adjective in workbook[‘Adjectives’][‘A’] if adjective.value is not None]
verb_list = [verb.strip().upper() for verb in workbook[‘Verbs’][‘A’] if verb.value is not None]

def get_random_word(word_list):
return random.choice(word_list)

def mad_libs_prompt():
while True:
user_input = input("Enter 1 for Noun, 2 for Adjective, 3 for Verb: ").strip().upper()

    if user_input in ['1', '2', '3']:
        break

    print("Invalid input. Please enter 1, 2, or 3.")

if user_input == '1':
    return get_random_word(noun_list)
elif user_input == '2':
    return get_random_word(adjective_list)
elif user_input == '3':
    return get_random_word(verb_list)

random_noun = mad_libs_prompt()
print(f"Random Noun: {random_noun}")

import pandas as pd
import random

lst_adjectives =
lst_nouns =
lst_verbs =

myworkbook = pd.ExcelFile(“Challenge88_Word_Lists.xlsl”) # loading the workbook

currentSheet = myworkbook.active # setting the active sheet

nouns = pd.read_excel(myworkbook, sheet_name=“Nouns”)
adjectives = pd.read_excel(myworkbook, sheet_name=“Adjectives”)
verbs = pd.read_excel(myworkbook, sheet_name=“Verbs”)

appending the lists

lst_nouns = nouns[“Words”].to_list()
lst1 = [string.strip() for string in lst_nouns]

lst_adjectives = adjectives[“Words”].to_list()
lst2 = [string.strip() for string in lst_adjectives]

lst_verbs = verbs[“Words”].to_list()
lst3 = [string.strip() for string in lst_verbs]

def randNoun():
select = random.choice(lst_nouns)
return select

def randAdj() :
select = random.choice(lst_adjectives)
return select

def randVerb() :
select = random.choice(lst_verbs)
return select

def randWord () :

type_of_word = int(input("Enter the number for any of the following verb(1), adjective(2), or noun(3)? "))

if (type_of_word < 0 or type_of_word > 3) : 
    print("This is an incorrect value!")

elif type_of_word == 1 : 
    print(randNoun())

elif type_of_word == 2 : 
    print(randAdj())

elif type_of_word == 3 : 
    print(randVerb()) 

returnQ = input("Do you want another word? ")[0].upper()

while returnQ == 'Y' : 
    randWord()
else:
    pass

main program

randWord()