Python

MadLib Exercise Using Python

Practice static exercise using Python string Template.

...

Here is a simple exercise to show how the template works for a static game of MadLibs. You could expand this exercise to have the user input each item as well.

Set Up the Python File "madlib_build.py":

The Python string Template is created by passing the template string to its constructor. It supports $-based substitutions. Here I'm using the template.safe_substitute method so that a KeyError is not thrown if a key is missing.


                from string import Template
                madlib_template_text = open('madlib_template.html').read()
                template = Template(madlib_template_text)

                mathlib_html = template.safe_substitute(
                    title="Hallowe'en",
                    plural_noun_1 = "pencils",
                    plural_noun_2 = "bananas",
                    plural_noun_3 = "cigars",
                    noun_1 = "grandfather clock",
                    noun_2 = "moped",
                    noun_3 = "scissors",
                    noun_4 = "eraser",
                    verb_1 = "dance",
                    verb_2 = "cook",
                    adverb_1 = "slowly",
                )
                open('madlib.html', 'w+').write(madlib_html)
              

Set Up the HTML Template Page "madlib_template.html"

I used Bootstrap for an easy display method. You'll notice that each variable maps/substitutes for each respective ${item-name}. For example, the &{title} relates to title = "Hallowe'en" in the Python file.

                                
                <html lang="en">
                <head>
                    <meta charset="utf-8"/>
                    <meta name="viewport" content="width=device-width, initial-scale=1"/>

                    <title>${title} - Mad Lib</title>
                    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

                </head>

                <body>
                    <div class="container">
                      <div class="row">
                        <div class="col">
                            <h1>${title} - Mad Lib</h1>
                         </div>

                        <div class="col-sm-8">
                            <p>Hallowe'en is my favourite holiday, because we get to dress up in ${plural_noun_1} and visit ${plural_noun_2} in our ${noun_1} saying "${noun_2} or ${noun_3}!"</p>
                            <p>I also love to ${verb_1} ${plural_noun_3} for hallowe'en! I use special carving tools to ${adverb_1} ${verb_2} a face into my ${noun_4}.</p>
                        </div>
                      </div>
                  </body>
                  </html>
              
I hope you have some fun with this exercise to reinforce the Python String Template concepts!