LIVE + LOVE + CODE!
Hey amazing people, today let's build a Random Story Generator using Python.
Our random story generator will use a few lists of phrases and every time we run our program, a sentence will be randomly formed by picking phrases from those lists. Again it's a fun and easy project so let's get into coding.
For this project, as we are going to randomly pick phrases, we need a module that can make our job easy. Any guesses which module I mean?
The random module! random module comes pre-installed with python hence we don't have to manually install it. Let's import it into our project.
Now it's time to define our lists which will contain random phrases.
when = ['A long time ago', 'Yesterday', 'Before you were born', 'In future', 'Before Thanos arrived'] who = ['Shazam', 'Iron Man', 'Batman', 'Superman', 'Captain America'] went = ['Arkham Asylum', 'Gotham City', 'Stark Tower', 'Bat Cave', 'Avengers HQ'] what = ['to eat a lot of cakes', 'to fight for justice', 'to steal ice cream', 'to dance']
Here we have defined 4 different lists but you can do more as per your choice. Also for phrases, I am using some random superhero theme phrases but again feel free to use your own.
Again, feel free to customize this part the way you like. You can add more scenes as lists as per your wish.
Now let's print the final output to see how our story turns out to be.
print(random.choice(when) + ', ' + random.choice(who) + ' went to ' + random.choice(went) + ' ' + random.choice(what) + '.')
Here we are making use of random.choice() function to randomly pick a phrase from the given list. We are also making use of + operator to concatenate (or combine) all the phrases so they come together & form a story.
Along with this, we are also adding a few strings in middle like spaces and commas to help our sentences appear good.
Here we go we did it!
You can find the complete source code of this project here -
Thank you so much for reading! I hope you found this beginner project useful.
If you like my work please consider Buying me a Coffee so that I can bring more projects, more articles for you.
Create your free account to unlock your custom reading experience.