Review, Formatting Silly Sentences


Voice Over     Well it’s a straight fight here at Leicester…On the left of the Returning Officer (camera shoes grey-suited man) you can see Arthur Smith, the Sensible candidate and his agent, (camera pans to silly people) and on the other side is the silly candidate Jethro Walrustitty with his agent and his wife.
Officer     Here is the result for Leicester. Arthur J. Smith…
Voice Over     Sensible Party
Officer     30,612…
Jethro Q. Walrustitty…
Voice Over     Silly Party
Officer     32,108.

We have been covering lots of new concepts very quickly. So now is the time to slow down a bit and go over some of the things we’ve already done, to have a look at them in a little more depth. In particular I want to try to give you some direction on how to make these code samples your own.

I also noticed that I did some things in the last tute which we haven’t encountered yet.  In particular, I:

  • assigned a function to an object r = random.randint.  Isn’t Python neat?  You can make these assignments, then the name r points at the function random.randint, so you can use r wherever you use the function.  Sometimes you can use this pattern to make your program run faster (honest!).  However, it might be confusing so I’ll stop it now!
  • used tab characters to format a print out: ‘\t’.  There are some “control” characters which modify the usual output of a set of printed characters.  Of particular interest are ‘\n’ (which makes a new line) and ‘\t’ which adds  a tab space. Try printing some strings with \n and \t in them to see what they do.

In this tutorial we’re going to look at formatting strings. In the previous tute we constructed a string by adding (using the ‘+’ operator) them together. Building strings this way can be a little challenging. Another way to do it, is to use formatting strings. We put place markers into a string, and match the place markers with values to go in there. The place markers are identfied by a % sign in the string, and values are added at the end after  a % sign. Here is a simple example:

>>> print '%s'%'hi'
hi

The string ‘hi’ is inserted in place of the %s (%s (the s is important – not just the % by itself) says insert a string here).  There are a number of different options for formatting other than %s (eg %f) but we’re not going into them here.  Read the documentation for more details.

 >>> print '->%s<-'%'This is the value which is inserted'
 ->This is the value which is inserted<-

We can define the format string and the value differently:

>>> formatString="...tell that to the young people of today, and %s."
>>> print formatString%"they won't believe you"
...tell that to the young people of today, and they won't believe you.

Then you can use the same format string with a different value.  This is useful when you have to print something repetitive, where only a part of it changes:

>>> print formatString%"they will fall about laughing"
 ...tell that to the young people of today, and they will fall about laughing.

You can put multiple values into the format string, but the values you supply must:

  • be in brackets ()  (this makes a thing called a tuple, but we haven’t seen them yet); and
  • have a comma between each of the values; and
  • there must be the same number of values as there are %s in the format string.
So, in the previous tute, we might have done something like this:
 >>> formatString="%s x %s = %s"
 >>> print formatString%(2,2,4)
 2 x 2 = 4

We can also pass variables to be printed as values to the formatting string:

 >>> i=2
 >>> j=3
 >>> print formatString%(i,j,i*j)
 2 x 3 = 6

So here’s the times table again:

 >>> for i in range(12):
 ...    for j in range(12):
 ...       print formatString%(i+1,j+1,(i+1)*(j+1))

Silly Sentences

Let’s adapt the silly sentence example from last tutorial.
Set up:
1. open your text editor,
2. open a new file
3. “save as” this empty file with the name “sillySentences110614.py”, save it in the p4k directory we’ve created to hold our stuff.

Now copy and paste this:

import random
nouns = ["apple","toy car","pumpernickel","dinner","pillow","homework","little finger","house","pencil","letterbox","hamster"]
verbs = ["ate","played","smelled","lost","forgot","dropped","hid","erased","infuriated","planted","ripped up","tripped over","dusted","talked to"]
v = len(verbs)-1
n = len(nouns)-1
numberOfSillySentences = 10
formatString = "I was very taken aback when Mrs Pepperpot %s my %s."

for i in range(numberOfSillySentences):
    verb = verbs[random.randint(0,v)]
    noun = nouns[random.randint(0,n)]
    print formatString%(verb,noun)

And save the file.  Can you see how much easier it is to get the spacing right?

Run the file by going to a console and typing:

> python sillySentences110614.py

Funny?

Now you need to make this code your own.

Exercise: First, change some of the verbs and nouns. You will see the pattern – for verbs you need to substitute doing words, and they need to be in the past – ate rather than eat.  For nouns you need to substitute words which name things.   Save the file, then run the program again from the console with:

> python sillySentences110614.py

Next, we’re going to change it to add some feelings in, but you have to supply the feelings:

Exercise: add some feeling words to the feelings arrray and run again:

import random
nouns = ["apple","toy car","pumpernickel","dinner","pillow","homework","little finger","house","pencil","letterbox","hamster"]
verbs = ["ate","played","smelled","lost","forgot","dropped","hid","erased","infuriated","planted","ripped up","tripped over","dusted","talked to"]
feelings=["very taken aback","very happy","quite sad"] # add more feelings to the array here 
v = len(verbs)-1
n = len(nouns)-1
f = len(feelings)-1 
numberOfSillySentences = 10
formatString = "I was %s when Mrs Pepperpot %s my %s."

for i in range(numberOfSillySentences):
  verb = verbs[random.randint(0,v)]  # choose a verb,noun, feeling  by calculating a random integer
  noun = nouns[random.randint(0,n)]  # between 0 and v,n,f (number of verbs,nouns, feelings)
  feeling = feelings[random.randint(0,f)]  
  print formatString%(feeling,verb,noun)  # substitute into the format string and print
About these ads

5 Responses to Review, Formatting Silly Sentences

  1. I have made a list of pronouns. I am trying to make it so that certain subject pronouns will use a slightly modified sentence so that it is grammatically correct but I keep receiving this error message.
    File “sillySentences1.py”, line 16,in (module)
    if pronoun == pronoun[1,4,5]:
    TypeError: sting indices must be integers, not tuple

    Here is my script:

    import random
    nouns = ["couch","basket","cup","wall","willow","dog","finger","book","leather","skin","ball"]
    verbs = ["vomitted","","muredered","ran","foraged","flopped","did","shot","infuriated","crushed","boiled","","dusted","talked to"]
    pronouns = ["I","You","She","He","They","We"]
    v = len(verbs)-1
    n = len(nouns)-1
    p = len(pronouns)-1
    numberOfSillySentences = 10
    formatString = “%s was very taken aback when Mrs Pepperpot %s my %s.”
    formatString1 = “%s were very taken aback when Mrs Pepperpot %s my %s”

    for i in range(numberOfSillySentences):
    verb = verbs[random.randint(0,v)]
    noun = nouns[random.randint(0,n)]
    pronoun = pronouns[random.randint(0,p)]
    if pronoun == pronoun[1,4,5]:
    print formatString1%(pronoun,verb,noun)
    else:
    print formatString%(pronoun,verb,noun)

    If i put just 1 = sign in my if statement it also goes wrong and the interpreter tells me to change it.
    I cant figure out whats wrong.

  2. brendanscott says:

    TypeError: sting indices must be integers, not tuple

    This type error doesn’t look right. However as it says the index (ie the thing in the []) must be an integer (ie a single number) not a tuple (like a list of numbers – I don’t think we’ve done tuples yet).

    Also, in your code there is no list called “pronoun” (without an s). Even if there was, pronoun[1,4,5] would not make any sense.

    Try making two lists of pronouns, then set pronouns = list1 + list2. Then try:
    if pronoun in list1:
    etc….

    Another way to do it is to save the index your creating with the random number and check whether it is “in [1,4,5]”

    Good luck!

  3. Pingback: MineCraft config editor part 2 « Python Tutorials for Kids 8+

  4. Pingback: Almost There! Adding Methods to Our Classes « Python Tutorials for Kids 8+

  5. Pingback: Put your child’s work on line with Web2py and Google Apps | Python for Dads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: