Choose Your Own Pyventure/Wandering Grue

Functions Case Study: Wandering Grue

Let's say you'd like to have a wandering Grue in your Mysterious House that randomly pops up in a room (or rooms).

One way to do this is to make a function that decides whether the Grue is in the room or not:

 Test Frameowrk 

Later in our complete code, we will see code similar to:

Here we introduce a new python data type:. Python booleans can take two values  and. These code fragments are equivalent:

if x > 3: print "yep!" if x > 3 is True: print "yep!" if bool(x>3) is True: print "yep!"

The "if" syntax implies if predicate is True. In Python, most things evaluate to, except:  None, False, 0 (0.0, etc.), empty strings, zero-length lists, dicts, and few other oddities.

Variation 1: not very random 

Our not very random grue always appears.

Exercise: Make the reverse -- a grue that never appears. The signature of the function should be

Variation 2: the 50/50 Grue 

So what does the random_grue function do? Let's try it. In the Python interpreter: >>> import random >>> def random_grue: n=random.random if n>0/5: grue = 1 else: grue = 0 return grue >>> random_grue 1

The first command is to import the random module, the second is to define the function and the third is to actually call the function. The 1 is the return of the function. You may get a 1 or a 0 depending on the number random generated. (Hint: try running it several times)

> A digression on pseudorandom numbers, and tips for getting the same ones every time!

Variation 2: the Moody Grue 

Note that we simplified down the function quite a bit by returning the boolean value directly (especially in 'grue_moody2'), rather than doing any conditional logic to get a 1 or 0. Also notices that we specified a default value for the argument.

Exercises


 * 1) Predict the behaviour of these functions calls.  Then try them.
 * 2) * grue_moody
 * 3) * grue_moody(-1)
 * 4) * grue_moody(1)
 * 5) * grue_moody("a")
 * 6) * grue_moody([1,2,3])
 * 7) Fix the code so that it prints an angry message and returns   if n is outside the interval (0,1).
 * 8) try  .  What do you see?
 * 9) what are the types of ,  ,

Variation 3: the location, location, location Grue 

In our final variation, we want a grue that:


 * has different percentages of appearing based on which page
 * should have zero chance of appearing in the main room "foyer"
 * should have a default chance of appearing of 5% in rooms that aren't otherwise described

Exercises


 * 1) as written,   has some bugs, and doesn't meet spec.  Identify and fix them.
 * 2) try:  location_grue('foyer', cutoffs=grue_fractions)
 * 3) what happens if 'room' isn't in 'cutoffs'?
 * 4) research the 'get' method of dictionarys...  .  Use this method to fix the code.