Re: Python: A Program I'd Love To Understand

  • From: "Littlefield, Tyler" <tyler@xxxxxxxxxxxxx>
  • To: programmingblind@xxxxxxxxxxxxx
  • Date: Thu, 23 Jun 2011 11:27:44 -0600

The only thing I want to comment on is the inherit. You can make any class, add an __call__ and that class can be called like a function. the __x__ methods are just to add extra functionality. As to your question about reading up on functions though, I do highly recommend you read up on dictionary/list/every thing else in the stdlib you can get your hands on. Someone might "know" a language, but they don't -really- know it until they know the stdlib that comes with the language.

On 6/23/2011 11:23 AM, R Dinger wrote:
Hi Jim,
My main concern at this point is that you understand the ideas in your sample program. I think the main idea was that you could use a dictionary like a switch statement or a chain of if...else if ... statements in other languages. As to the functions that begin with double underscores like __cmp__, I think that may be too advanced for now. These functions are mainly used when you inherit from a class like dict or list, but want to customize some default behaviors. You may have better luck looking for information on dictionaries if you use the keyword 'dict' like help(dict) for the whole class or help(dict.keys) for a specific method. Note you can substitute '{}' for 'dict' in the help command (or [] for lists etc.).
Richard
----- Original Message -----
*From:* Homme, James <mailto:james.homme@xxxxxxxxxxxx>
*To:* programmingblind@xxxxxxxxxxxxx <mailto:programmingblind@xxxxxxxxxxxxx>
*Sent:* Thursday, June 23, 2011 8:42 AM
*Subject:* RE: Python: A Program I'd Love To Understand

Hi Richard,

I think I understand the program I was showing for the most part. Would it do me good to try to read about those functions attached to strings, lists, dictionaries, and functions that start with underscores? I tried to go into the Python help yesterday that is inside the interpreter. When I got there, I typed topics. One of them was dictionaries. I typed the word dictionaries, and it said that it had no documentation about that. I popped open the Python Standard Library documentation and found where it talks about dictionaries. I didn't see the part where it talks about those special functions. My next move might be to see if I can make a little script that dumps out the doc strings for the functions that get listed when you run the dir function. That might be a good exercise for someone at my current level. Do you have any other suggestions?

Thanks.

Jim

*From:*programmingblind-bounce@xxxxxxxxxxxxx [mailto:programmingblind-bounce@xxxxxxxxxxxxx] *On Behalf Of *R Dinger
*Sent:* Thursday, June 23, 2011 11:02 AM
*To:* programmingblind@xxxxxxxxxxxxx
*Subject:* Re: Python: A Program I'd Love To Understand

Hi Jim,

Are you clear now on how your demo program works?

Richard

----- Original Message -----

*From:*Homme, James <mailto:james.homme@xxxxxxxxxxxx>

*To:*programmingblind@xxxxxxxxxxxxx <mailto:programmingblind@xxxxxxxxxxxxx>

*Sent:*Wednesday, June 22, 2011 12:41 PM

*Subject:*RE: Python: A Program I'd Love To Understand

Hi,

Now, here's the whole program.

I think that normally, you would loop from start to finish in the dictionary, but it looks like any time one of the functions at the top of the program returns the death function, that makes the loop terminate. It seems like this code would be easy to break to me. I'd rather make a variable and not go around changing stuff, but my computer science knowledge has lots of holes. I'd maybe feel better if I would loop from start to finish and sometimes do nothing. Maybe I don't know what I'm talking about, which is likely.

# ex41.py

# Bring in the exit function from sys

from sys import exit

# Bring in randint from the random function.

from random import randint

def death():

  """Print a random death message and exit out of the program."""

  print "Top of death function."

# This is a list of strings.

  quips = ["You died.  You kinda suck at this.",

    "Your mom would be proud. if she were smarter.",

    "Such a loser.",

    "I have a small puppy that's better at this."]

# print a random string from the list.

# len gives us the number of items in the list.

# But the last item in the list is one below that.

# So call randint, then subtract one and we will get one of the strings in the list.

  print quips[randint(0, len(quips)-1)]

  # Exit with a return code other than 0.

  exit(1)

def princess_lives_here():

  """Princess room."""

  print "Top of princess lives here function."

  print "You see a beautiful Princess with a shiny crown."

  print "She offers you some cake."

  eat_it = raw_input("> ") # Let the user type something.

  if eat_it == "eat it":

    print "You explode like a pinata full of frogs."

    print "The Princess cackles and eats the frogs. Yum!"

    return 'death'  # I'm not sure why there are no parentheses.

  elif eat_it == "do not eat it":

    print "She throws the cake at you and it cuts off your head."

    print "The last thing you see is her munching on your torso. Yum!"

    return 'death'

  elif eat_it == "make her eat it":

    print "The Princess screams as you cram the cake in her mouth."

    print "Then she smiles and cries and thanks you for  saving her."

    print "She points to a tiny door and says, 'The Koi needs cake too.'"

    print "She gives you the very last bit of cake and shoves you in."

    return 'gold_koi_pond'

  else:

print "The princess looks at you confused and just points at the cake."

    return 'princess_lives_here' # Is this recursion?

def gold_koi_pond():

  print "Top of gold koy [pond function."

  print "There is a garden with a koi pond in the center."

  print "You walk close and see a massive fin poke out."

  print "You peek in and a creepy looking huge Koi stares at you."

  print "It opens its mouth waiting for food."

  feed_it = raw_input("> ")

  if feed_it == "feed it":

print "The Koi jumps up, and rather than eating the cake, eats your arm."

    print "You fall in and the Koi shrugs than eats you."

    print "You are then pooped out sometime later."

    return 'death'

  elif feed_it == "do not feed it":

    print "The Koi grimaces, then thrashes around for a second."

print "It rushes to the other end of the pond, braces against the wall..."

print "then it *lunges* out of the water, up in the air and over your"

    print "entire body, cake and all."

    print "You are then pooped out a week later."

    return 'death'

  elif feed_it == "throw it in":

    print "The Koi wiggles, then leaps into the air to eat the cake."

    print "You can see it's happy, it then grunts, thrashes..."

    print "and finally rolls over and poops a magic diamond into the air"

    print "at your feet."

    return 'bear_with_sword'

  else:

    print "The Koi gets annoyed and wiggles a bit."

    return 'gold_koi_pond'

def bear_with_sword():

  print "Top of bear with sword function."

  print "Puzzled, you are about to pick up the fish poop diamond when"

  print "a bear bearing a load bearing sword walks in."

  print'"Hey! That\' my diamond! Where\'d you get that!?"'

  print "It holds its paw out and looks at you."

  give_it = raw_input("> ")

  if give_it == "give it":

    print "The bear swipes at your hand to grab the diamond and"

    print "rips your hand off in the process.  It then looks at"

    print 'your bloody stump and says, "Oh crap, sorry about that."'

    print "It tries to put your hand back on, but you collapse."

    print "The last thing you see is the bear shrug and eat you."

    return 'death'

  elif give_it == "say no":

    print "The bear looks shocked.  Nobody ever told a bear"

    print "with a broadsword 'no'.  It asks, "

    print '"Is it because it\'s not a katana?  I could go get one!"'

    print "It then runs off and now you notice a big iron gate."

    print '"Where the hell did that come from?" You say.'

    return 'big_iron_gate'

  else:

    print "The bear look puzzled as to why you'd do that."

    return "bear_with_sword"

def big_iron_gate():

  print "Top of big iron gate function."

  print "You walk up to the big iron gate and see there's a handle."

  open_it = raw_input("> ")

  if open_it == 'open it':

    print "You open it and you are free!"

    print "There are mountains.  And berries! And..."

    print "Oh, but then the bear comes with his katana and stabs you."

    print '"Who\'s laughing now!?  Love this katana."'

    return 'death'

  else:

    print "That doesn't seem sensible.  I mean, the door's right there."

    return 'big_iron_gate'

# A dictionary of functions to call.

ROOMS = { 'death': death,

  'princess_lives_here': princess_lives_here,

  'gold_koi_pond': gold_koi_pond,

  'big_iron_gate': big_iron_gate,

  'bear_with_sword': 'bear_with_sword'

  }

def runner(map, start):

  # Loop through the dictionary and call each function.

print "Top of runner function." # For understanding what's going on. Remove later

  # next will be the first function of the dictionary.

  next = start

# I think that the condition will be False once we have no more functions to loop through.

  while True:

    print "Top of loop: next is now %s." % next # Remove later.

room = map[next] # Get the name of the function we are going to call further down.

    print "Room is now %s." % room # Remove later.

    print "\n--------"

    next = room() # Call the function and get back what it returns.

    print "Bottom of loop: next is now %s." % next

# Call runner. Give it the dictionary, and which key to start with.

runner(ROOMS, 'princess_lives_here')

*From:*programmingblind-bounce@xxxxxxxxxxxxx [mailto:programmingblind-bounce@xxxxxxxxxxxxx] *On Behalf Of *R Dinger
*Sent:* Wednesday, June 22, 2011 2:17 PM
*To:* programmingblind@xxxxxxxxxxxxx
*Subject:* Re: Python: A Program I'd Love To Understand

Jim,

Your dictionary entries are all of the form:

'key': target

Your keys must be immutable like a string, tuple, number and so forth.

Your target can be almost anything like a string, tuple, list, function and so forth. Since your targets are not quoted, they are not strings. In addition each target, like death, must have been defined previously in your current module or some module you have already imported.

HTH

Richard

The ----- Original Message -----

*From:*Homme, James <mailto:james.homme@xxxxxxxxxxxx>

*To:*programmingblind@xxxxxxxxxxxxx <mailto:programmingblind@xxxxxxxxxxxxx>

*Sent:*Wednesday, June 22, 2011 10:59 AM

*Subject:*Python: A Program I'd Love To Understand

Hi,

I have lots of questions about the current Python exercise I'm working on, so I'll just ask one at a time. Hope you have lots of patience.

First question. I think I should be getting a compiler error but I'm not. I thought I had to put some sort of quotes around this code after the commas. Why is this compiling OK?

ROOMS = { 'death': death,

  'princess_lives_here': princess_lives_here,

  'gold_koi_pond': gold_koi_pond,

  'big_iron_gate': big_iron_gate,

  'bear_with_sword': bear_with_sword

  }

Thanks.

Jim

Jim Homme,

Usability Services,

Phone: 412-544-1810.

This e-mail and any attachments to it are confidential and are intended solely for use of the individual or entity to whom they are addressed. If you have received this e-mail in error, please notify the sender immediately and then delete it. If you are not the intended recipient, you must not keep, use, disclose, copy or distribute this e-mail without the author's prior permission. The views expressed in this e-mail message do not necessarily represent the views of Highmark Inc., its subsidiaries, or affiliates.



--

Take care,
Ty
my website:
http://tds-solutions.net
my blog:
http://tds-solutions.net/blog
skype: st8amnd127
My programs don't have bugs; they're randomly added features!

Other related posts: