Mini-Project/Homework
Create the lists noun, verb, adjective, and adverb, and give them as many elements as you want.
Import the random module. (We’ll be using random.choice() to select random words from the lists.)
Open a file called “madlibs.txt”. Since it doesn’t already exist and you want to be able to read it afterward, what mode should you use?
Write lines into it that create your story. Remember to add a new line character after each line!
Each line should contain one randomly selected word from the list.
Ex: f.write(f'Once upon a time, there was a {random.choice(adj)} {random.choice(noun)} in my backyard.\n')
Read the entire file after the story is finished. Make sure the cursor starts at 0.
Resources:
Slides: https://docs.google.com/presentation/d/1GJ0GfDy0XPqqW4byO-bFVEkw1LwE_lX0VQo3sC5Beq8/edit?usp=sharing
Class code: https://replit.com/join/nbrzbntycr-shrav816
Contact Info:
shravyassathish@gmail.com (mentor)
kingericwu@gmail.com (TA)
felixguo41@gmail.com (TA)
noun = ["Christmas", "holiday", "entertainment", "Python", "neighbor", "computer", "hologram", "reindeer", "sleigh", "jar", "stock", "picture", "galaxy"]
verb = ["killing", "finding", "riding", "seeking", "coding", "wiping", "opening", "creating", "deleting", "ending", "playing", "saying", "elating", "striking"]
adjective = ["good", "bad", "evil", "beautiful", "ugly", "angry", "agitated", "frustrated", "elegant", "festive", "cheerful", "elevated", "moody"]
adverb = ["surprisingly", "severely", "coolly", "quickly", "scarily", "often", "irritatingly", "probably", "only", "searingly", "painfully", "joyfully"]
import random
f = open("madlibs.txt", "w+")
f.writelines([f"A long time ago in a {random.choice(noun)} far, far away....\n",
f"It was a(n) {random.choice(adjective)} {random.choice(adjective)} day in April, and the {random.choice(noun)}s were {random.choice(verb)} thirteen.\n",
f"The {random.choice(adjective)} {random.choice(noun)} named {random.choice(noun)} was {random.choice(adverb)} {random.choice(verb)}, surprisingly enough. ",
f"We musn't be {random.choice(verb)} them for this, for they are a quite a {random.choice(adjective)} character. But as {random.choice(noun)} is {random.choice(adverb)} {random.choice(verb)} them, the heroic {random.choice(noun)} {random.choice(adverb)} ends up {random.choice(verb)} both of them, ending a {random.choice(adjective)} era for the galaxy."
])
f.seek(0)
print(f.read())