PROJECT 8
Silly Sentences
In this project you’re going to put together a program that spits out a hilarious mixture of words — sort of like Mad Libs. To do this, you’re going to tackle string formatting for prettier printing.
This project’s object is to create templates for words that are randomly chosen from a list. The randomness of the words makes them absurd and, hopefully, funny enough to make you laugh out loud.
To complete this project, you
- Read about Python formatting strings.
- Create templates for the formatting strings.
- Create lists of words to put into the formatting strings.
- Choose words at random.
- Print the words into the template using formatting.
Insert Format Strings
Format strings let you fit changeable bits of a message into a template. That way it’s easier to present your messages, and it makes your code more readable.
Fire up IDLE. At the interpreter, type the following and be careful — there are two strings. The first is "Hi there %s. You are such a good author." and the second is "Brendan". In between them is the % character.
>>> print("Hi there %s. You are such a good author."%"Brendan")
Hi there Brendan. You are such a good author.
Why, thank you. That’s a very kind thing to say.
Can you see what has happened there? The second string ("Brendan") was substituted into the first string in the place where the %s was.
Get Python For Kids For Dummies now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.