# 88|PYTHON – Mad Libs Help

**URL:** <https://www.techhub.training/t/88-python-mad-libs-help/646>\
**Category:** Challenges\
**Tags:** beginner, python, functions, user-input, loops\
**Created:** [May 12, 2023, 6:39am UTC](https://www.techhub.training/t/88-python-mad-libs-help/646 "2023-05-12T06:39:56Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![IWillyerd](https://sea2.discourse-cdn.com/flex016/user_avatar/www.techhub.training/iwillyerd/32/81_2.png) [@IWillyerd](https://www.techhub.training/u/IWillyerd)\
**Post date:** [May 12, 2023, 6:39am UTC](https://www.techhub.training/t/88-python-mad-libs-help/646/1 "2023-05-12T06:39:56Z")

</div>

_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](https://colab.research.google.com/) 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](https://www.techhub.training/t/information-about-software-used-on-techhub-training/138).

**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**
>
> ```auto
> #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**
>
> ```auto
> #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**

- [Challenge88\_Word\_Lists.xlsx](https://byu.box.com/shared/static/4ulju8zwb4lobjce2rauoi1zqpswe3dt)

**Solution**

> **Solution Code**
>
> ```auto
> #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](https://byu.box.com/shared/static/zxe2c2fvaxast29tpqtguxp4iff7soe9)  
_Solution Video:_ [Challenge 88|PYTHON – Mad Libs Help](https://youtu.be/hjFdUlfysOo)

---

<div class="post-metadata">

**Author:** ![Bdonlpez](https://sea2.discourse-cdn.com/flex016/user_avatar/www.techhub.training/bdonlpez/32/6892_2.png) [@Bdonlpez](https://www.techhub.training/u/Bdonlpez)\
**Post date:** [October 31, 2023, 6:07pm UTC](https://www.techhub.training/t/88-python-mad-libs-help/646/2 "2023-10-31T18:07:27Z")

</div>

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](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/8/85d9571067d40974d63f70d8f3df8cbfdb54af0c.png)

---

<div class="post-metadata">

**Author:** ![Lauren\_Woodbury](https://avatars.discourse-cdn.com/v4/letter/l/ba8739/32.png) [@Lauren\_Woodbury](https://www.techhub.training/u/Lauren_Woodbury)\
**Post date:** [December 8, 2023, 5:00am UTC](https://www.techhub.training/t/88-python-mad-libs-help/646/3 "2023-12-08T05:00:55Z")

</div>

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!

 ![ChallengeSolution](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/1/13f7e25c863828de3403aba2253f8404c58aa16f.png)

---

<div class="post-metadata">

**Author:** ![lizzyxhall](https://avatars.discourse-cdn.com/v4/letter/l/d6d6ee/32.png) [@lizzyxhall](https://www.techhub.training/u/lizzyxhall)\
**Post date:** [December 9, 2023, 9:36pm UTC](https://www.techhub.training/t/88-python-mad-libs-help/646/4 "2023-12-09T21:36:19Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![Riley\_Croft](https://avatars.discourse-cdn.com/v4/letter/r/51bf81/32.png) [@Riley\_Croft](https://www.techhub.training/u/Riley_Croft)\
**Post date:** [December 13, 2023, 7:11pm UTC](https://www.techhub.training/t/88-python-mad-libs-help/646/5 "2023-12-13T19:11:37Z")

</div>

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}")

 ![image](https://us1.discourse-cdn.com/flex016/uploads/weeklytechchallenge/original/2X/9/968f3270952ac6b9e57c5373bb99f65f24b792df.png)

---

<div class="post-metadata">

**Author:** ![Amy\_Tracy](https://sea2.discourse-cdn.com/flex016/user_avatar/www.techhub.training/amy_tracy/32/7589_2.png) [@Amy\_Tracy](https://www.techhub.training/u/Amy_Tracy)\
**Post date:** [December 13, 2023, 10:15pm UTC](https://www.techhub.training/t/88-python-mad-libs-help/646/6 "2023-12-13T22:15:22Z")

</div>

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}")

---

<div class="post-metadata">

**Author:** ![Carson\_Connors](https://avatars.discourse-cdn.com/v4/letter/c/7ba0ec/32.png) [@Carson\_Connors](https://www.techhub.training/u/Carson_Connors)\
**Post date:** [April 9, 2024, 4:30am UTC](https://www.techhub.training/t/88-python-mad-libs-help/646/7 "2024-04-09T04:30:58Z")

</div>

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()
