Re: [Tutor] What's wrong with this code?

2005-07-05 Thread Brian van den Broek
Andre Engels said unto the world upon 05/07/2005 02:44:
>>From the program::
> 
> answer = raw_input("What is the password? ")
> while password != answer:
> print "The password is incorrect."



> I think you intended to make it so that
> the program kept asking for passwords until the right one was given.
> This is done with:
> answer = raw_input("What is the password? ")
> while password != answer:
> print "The password is incorrect."
> answer = raw_input("What is the password? ")


A small thing, but I think that is better as:

while True:
  answer = raw_input("What is the password? ")
  if password == answer:
  break
  print "The password is incorrect."

It probably runs a bit slower, but who cares, as the bottleneck is in 
the chair, not the chip. The advantage is that there is only one 
statement of the prompt to alter if you wanted to change it later.

But, I think this will be one where reasonable people can differ. 
Andre's version does make the semantics of the loop somewhat more obvious.

Best to all,

Brian vdB



> Andre Engels




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] "And" function

2005-07-05 Thread gordnjen



I need to write a program that will do the 
following:
 
Ask the user's age.
If their age is below 1 yr old, it prints 
"you are old enought to eat baby food"
If they are over 16, it prints "You are old 
enough to drive"
If they are over 65, it prints "You are old 
enough to drive" and "You are old enough to retire"
 
If they are between the ages of 16 and 25, 
it prints "you are old enough to get a student discount".
 
So far, I have this:
 
age =int(raw_input("How old are 
you?"))if age>16:    print "You are old enough to 
drive!"    if 
age>65:    print "You are old 
enough to retire!"    if 
age<1:    
print "You are old enough to eat baby food!"
 
 
I get stuck with the old enough to get a 
student discount part. I have tried
 
if age>16 and age<25:
print "You are old enough to get a student 
discount"
 
But it doesn't seem to work.
 
Any help would be great.
 
Thanks!
 
Jennine
 
 






--
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.323 / Virus Database: 267.8.9/39 - Release Date: 04/07/2005
 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "And" function

2005-07-05 Thread Brian van den Broek
gordnjen said unto the world upon 04/07/2005 22:24:
> I need to write a program that will do the following:
>  
> Ask the user's age.
> If their age is below 1 yr old, it prints "you are old enought to eat baby
> food"
> If they are over 16, it prints "You are old enough to drive"
> If they are over 65, it prints "You are old enough to drive" and "You are
> old enough to retire"
>  
> If they are between the ages of 16 and 25, it prints "you are old enough to
> get a student discount".


Hi Jennine,

> So far, I have this:
>  
> age =int(raw_input("How old are you?"))
> if age>16:
> print "You are old enough to drive!"
> if age>65:
> print "You are old enough to retire!"
> if age<1:
> print "You are old enough to eat baby food!"


And this works? Is it your actual code? I ask as it seems to me as 
though if age = 0.5, age > 16 will evaluate as False, and the flow 
will never get to if age < 1.


> I get stuck with the old enough to get a student discount part. I have tried
>  
> if age>16 and age<25:
> print "You are old enough to get a student discount"
>  
> But it doesn't seem to work.


Can you define "doesn't work"? Did you get a syntax error? Or just not 
the behaviour you expected?

Unless your fancy html mail (please don't do that when posting here, 
by the way) stripped the indents, the problem is you didn't indent 
your print statement into the if block. Witness:

 >>> num = 97
 >>> if num > 10 and num < 30:
... print "In the range"
...
 >>> num = 20
 >>> if num > 10 and num < 30:
... print "In the range"
...
In the range
 >>>

Even better is:

 >>> if 10 < num < 30:
... print "Still there"
... 
Still there
 >>>

HTH,

Brian vdB


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "And" function

2005-07-05 Thread geon




gordnjen napsal(a):

  
  Message
  
  
  I need to write a program that
will do the following:
   
  Ask the user's age.
  If their age is below 1 yr old,
it prints "you are old enought to eat baby food"
  If they are over 16, it prints
"You are old enough to drive"
  If they are over 65, it prints
"You are old enough to drive" and "You are old enough to retire"
   
  If they are between the ages of
16 and 25, it prints "you are old enough to get a student discount".
   
  So far, I have this:
  

what about this:


   
  age =input("How old are you?")
if age>16:
    print "You are old enough to drive!"
    if age>65:
    print "You are old enough to retire!"
if age<1:
   print "You are old enough to eat baby food!"
   
   
  

If's those are on the same logical level should be also on the same
vertical level :-)

Pavel



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Initialising attributes with random values

2005-07-05 Thread Max Russell
Hello there;

If I have a class and want to initalise it, with
random values assigned to the attributes, what is the
best way of doing this?

For example:

def __init__(self, name, size = 0, strength = 0):
self.name = name
self.size = size
self.strength = strength

starts with values of 0. But how can I neatly say,
start with a random value from (for example) 1 - 5?

thanks
Max



___ 
How much free photo storage do you get? Store your holiday 
snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Initialising attributes with random values

2005-07-05 Thread Pujo Aji
use : 

random.randint(1,5)

so complete code will be:

class something:
def __init__(self, name):
self.name = name
self.size = random.randint(1,5)
self.strength = random.randint(1,5)



pujo

On 7/5/05, Max Russell <[EMAIL PROTECTED]> wrote:
> Hello there;
> 
> If I have a class and want to initalise it, with
> random values assigned to the attributes, what is the
> best way of doing this?
> 
> For example:
> 
> def __init__(self, name, size = 0, strength = 0):
> self.name = name
> self.size = size
> self.strength = strength
> 
> starts with values of 0. But how can I neatly say,
> start with a random value from (for example) 1 - 5?
> 
> thanks
> Max
> 
> 
> 
> ___
> How much free photo storage do you get? Store your holiday
> snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] more() method of asynchat

2005-07-05 Thread Johan Geldenhuys




Hi all,
I am trying to use the asynchat and asyncore modules in the documentation it says that one must create the producers (connection) own more() method.

What does this do and do I need to have it?

Thanks,

Johan


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Case ?

2005-07-05 Thread Mike Cheponis
Why does Python not have a "case" statement, like C?

Thanks!  -Mike
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Case ?

2005-07-05 Thread Danny Yoo


On Tue, 5 Jul 2005, Mike Cheponis wrote:

> Why does Python not have a "case" statement, like C?


Hi Mike,

It's a proposed enhancement:

http://www.python.org/peps/pep-0275.html


That being said, a dispatch-table approach, using a dictionary, works well
in Python because it's not hard to use functions as values --- most people
haven't really missed case/switch statements in Python because dispatch
tables can be very effective.


For example, something like this:

### C ###
switch(state) {
case STATE_1: doStateOneStuff();
  break;
case STATE_2: doStateTwoStuff();
  break;
case STATE_3: doStateThreeStuff();
  break;
default:  doDefaultAction();
##


has a natural translation into Python as:

### Python ###
dispatchTable = { STATE_1: doStateOneStuff,
  STATE_2: doStateTwoStuff,
  STATE_3: doStateThreeStuff }
command = dispatchTable.get(state, doDefaultAction)
command()
##

where we're essentially mimicking the jump table that a case/switch
statement produces underneath the surface.


One other consideration about C's case/switch statement is its
bug-proneness: it's all too easy to programmers to accidently forget to
put 'break' in appropriate places in there.


Hope this helps!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I sure do love cookies.

2005-07-05 Thread D. Hartley
Thank you for the code, everyone.

I actually have a piece of information (something like
"this+is+a+cookie") that I am trying to *send* (not receive), and I'm
not sure how to do it.  I looked at the Cookie examples a little bit,
but am having trouble applying what I see there to my present
situation, since there is so much that either a). doesnt apply or b).
is over my head (usually c). all of the above!). Although the
client-side illustration you provided was very clear and I'll archive
that for future use, too.

So, for *sending* cookies, it seems that I would want to create one this way:

##
>>> import Cookie
>>> mycookie = Cookie.SimpleCookie()
>>> mycookie['value'] = 'this+is+a+cookie'
>>>
>>> mycookie

>>>
>>> print mycookie
Set-Cookie: value=this+is+a+cookie;
##

But then what? How do I send this anywhere? Right now it seems to be
just a thing sitting in my python screen, and not something that
actually does anything. If I have correctly created a cookie (have
I?), what do I do with it now?

Thanks,
Denise

On 7/4/05, Liam Clarke <[EMAIL PROTECTED]> wrote:
> Hi, 
> 
> Denise, if you're handling cookies client side, then this is how to do it
> (code snippets taken from
> http://www.voidspace.org.uk/python/articles/cookielib.shtml
> as I'm at work.)
> 
> import os.path
> import urllib2
> import cookielib
> 
> 
> COOKIEFILE = 'cookies.lwp'
> # the path and filename to save your cookies in
> 
> urlopen = urllib2.urlopen
> Request = urllib2.Request
> cj = cookielib.LWPCookieJar( )
>  # This is a subclass of FileCookieJar
>  # that has useful load and save methods
> 
> if os.path.isfile (COOKIEFILE):
>  # if we have a cookie file already saved
>  # then load the cookies into the Cookie Jar
>  cj .load(COOKIEFILE)
> 
> opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj)) 
> urllib2.install_opener(opener)
> 
> #The above two lines initialise a opener which can handle cookies, and will
> use our cookie jar
> 
> theurl =
> 'http://www.google.co.uk/search?hl=en&ie=UTF-8&q=voidspace&meta=
> '
> # an example url that sets a cookie,
> # try different urls here and see the cookie collection you can make !
> 
> txdata = None
> # if we were making a POST type request,
> # we could encode a dictionary of values here,
> # using urllib.urlencode(somedict)
> 
> txheaders =  {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows
> NT)'}
> # fake a user agent, some websites (like google) don't like automated
> exploration
> 
> try:
> req = Request(theurl, txdata, txheaders)
> # create a request object
> 
> handle = urlopen(req)
> # and open it to return a handle on the url
> 
> except IOError, e:
> print 'We failed to open "%s".' % theurl
> if hasattr(e, 'code' ):
> print 'We failed with error code - %s.' % e. code
> elif hasattr(e, 'reason' ):
> print "The error object has the following 'reason' attribute :"
> print e.reason
> print "This usually means the server doesn't exist,',
> print "is down, or we don't have an internet connection."
> sys.exit()
> 
> else:
> print 'Here are the headers of the page :'
> print handle.info()
> # handle.read() returns the page
> # handle.geturl() returns the true url of the page fetched
> # (in case urlopen has followed any redirects, which it sometimes does)
> 
> print
> if cj is None:
> print "We don't have a cookie library available - sorry."
> print "I can't show you any cookies."
> else:
> print 'These are the cookies we have received so far :'
> for index, cookie in enumerate (cj):
> print index, '  :  ', cookie
> cj.save(COOKIEFILE)  
> 
> 
> 
> -
> 
> Phew! A bit of code, but that shows a simple usage(!) of it.
> 
> Good luck.
> 
> 
> On 7/5/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> > Danny Yoo wrote:
> > > To make cookies, in the examples of the Cookie module will probably help
> > > the most:
> > >
> > > http://www.python.org/doc/lib/cookie-example.html 
> > >
> > >>From the documentation, it sounds like Cookie.SimpleCookie is what
> you're
> > > looking for:
> > 
> > My understanding is that the Cookie module is for server-side cookie
> handling. cookielib.Cookie integrates with cookielib.CookieJar for
> client-side cookie handling which is what Denise is looking for. Though
> possibly I am missing something...
> > 
> > Kent
> > 
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> 
> 
> 
> -- 
> 'There is only one basic human right, and that is to do as you damn well
> please.
> And with it comes the only basic human duty, to take the consequences.' 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailm

[Tutor] Handling Unpickled Data

2005-07-05 Thread Don Parris
Greetings,

I have a script that gets a little info from the user, using a
dictionary, which I then store in a file via cPickle.  This pickle
concept must be good for something, but I haven't figured out exactly
what just yet.  At any rate, I would like to now get the code and be
able to display only one value for the user.

I thought I could do this by specifying a key in orginfo.  However,
the function throws all the data to stdout, not just the desired key. 
How can I limit the output to just the value of the key I want to
reference?  Do I need to create a for or while loop, or an if
statement to say, "extract this key:value pair only"?

I can also get this from a SQL query, but since I couldn't do it with
a file, I wanted to try and figure it out.  The book, "Learning
Python" is very helpful, now that I have it, but it kind of breezed
past this kind of thing.  I really would like to understand how to
work with the data in the text file.

### function def ###
def org_Get_Info():
orgGdata = open('orgdata.txt', 'r')
orginfo = cPickle.load(orgGdata),
orgGdata.close()
print orginfo['Name']  # this is really all I want.

### Output at DOS prompt ###
Organization Name: ocf  # Begin input
Address: 6123
City: char
State: nc
Zip: 282
City :  char   # Begin output from org_Get_Info()
State :  nc
Name :  ocf
Zip :  282
Address :  6123
ocf # this is all I want - not the rest.


Thanks,
Don
-- 
DC Parris GNU Evangelist
http://matheteuo.org/
[EMAIL PROTECTED]
Free software is like God's love - 
you can share it with anyone anywhere anytime!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling Unpickled Data

2005-07-05 Thread Don Parris
On 7/5/05, Don Parris <[EMAIL PROTECTED]> wrote:
> Greetings,
> 
> I have a script that gets a little info from the user, using a
> dictionary, which I then store in a file via cPickle.  This pickle
> concept must be good for something, but I haven't figured out exactly
> what just yet.  At any rate, I would like to now get the code and be
> able to display only one value for the user.
> 

Never mind.  I had set a print statement in the other function way
back when, and did not think about that as I looked at my code.  Duh! 
Yes, I'm a newbie. :)

Don
-- 
DC Parris GNU Evangelist
http://matheteuo.org/
[EMAIL PROTECTED]
Free software is like God's love - 
you can share it with anyone anywhere anytime!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I sure do love cookies.

2005-07-05 Thread Kent Johnson
D. Hartley wrote:
> Thank you for the code, everyone.
> 
> I actually have a piece of information (something like
> "this+is+a+cookie") that I am trying to *send* (not receive), and I'm
> not sure how to do it.  I looked at the Cookie examples a little bit,
> but am having trouble applying what I see there to my present
> situation, since there is so much that either a). doesnt apply or b).
> is over my head (usually c). all of the above!). Although the
> client-side illustration you provided was very clear and I'll archive
> that for future use, too.

Did you see the hint I posted a few days ago? I'll repeat it, if you want more 
detail then ask but after all it's supposed to be a challenge :-)

What I did was,
- create a new cookielib.Cookie
- add the cookie to the CookieJar
- make a request the same way as when I was collecting cookies

To create the new Cookie it might help to look at the source for cookielib 
(Lib\cookielib.py), the Cookie constructor doesn't seem to be documented 
anywhere.

To figure out the values for the Cookie constructor it might help to look at 
one of the cookies you already have.

I could be wrong but I don't think Cookie.SimpleCookie is going to get you 
there.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: A more Pythonic way to do this

2005-07-05 Thread D. Hartley
This question began on the tutor mailing list, but I am now seeing
that it is pygame-specific, so I am forwarding it here as well. I
apologize if anyone gets a duplicate post.

As it turns out, my "holder" classes are all subclasses of type
RenderClear (which it says is "basic Group class you will want to
use."  My "group" was "enemyship_sprites," which I discovered could
not be iterated over.  However, if I used
"enemyship_sprites.sprites()" instead, I *can* iterate over that - it
creates a list of all the sprites in my group (according to the docs),
so I could use this in len(enemyship_sprites.sprites()) to count the
number of enemy ships I had on the screen and so on.

So what I am trying to do is take all of the enemy ships left on the
screen that have not been killed in this particular level (i.e., when
one of them drops too low on the screen and kills the hero - a space
invaders-style game), and reset it to its own starting position for
that level.  So I created variables in my Enemy class called initialx
and initialy (given default values of 0 and then updated when the
Enemy is actually drawn on screen), and when the bad guys drop down
too low, I inserted this for loop:

for each in (enemyship_sprites.sprites()):
each.rect.centerx = Enemy.initialx
each.rect.centery = Enemy.initialy

Then I draw the enemyship_sprites like I always did. (Before, it just
redrew ALL the enemies for that level, effectively restarting the
level with a full screen of baddies. I want to take just the ones that
havent been killed yet and return them to their original position).

My problem at first was I was just doing  for each in
(enemyship_sprites): - which would not work because I can't iterate
over it. Now apparently I *am* iterating over the list of sprites I
have at this point (I think, if I am doing it correctly, it should be
the list of enemies which has not yet been killed on this level), and
should be returning each to its original starting position. Since I
create initialx/initialy for each enemy when the screen full of
enemies is drawn (and I know I do create a new initialx/initialy for
each one - because I had it print the initialx, initialy when the
screen was drawn and I get 40 sets of values printed for the 40
enemies on the screen), wouldnt each instance of the Enemy class store
its own initialx initialy so that when I called
each.rect.centerx = Enemy.initialx
each.rect.centery = Enemy.initialy
.. it would return each to its own starting position?

Right now, it seems to be printing them all right on top of the other,
in one enemy position.  At first I thought I was redrawing only one
enemy, but I shot it, and there seems to be another underneath it. A
lot of others, actually.  So I can't even see if it is drawing just
the ones that havent been killed yet or a whole new batch.  And,
obviously, it's not relocating them correctly :P

Am I understanding this wrong? Is it only storing the last-computed
initialx/initialy and restoring all enemies there? Should I be using
something other than pygame.sprite.RenderClear as my 'super group'? Am
I going about this in the totally wrong way?

Any pointers/suggestions/things to try would be appreciated!

Thanks,
Denise

-- Forwarded message --
From: Adam Bark <[EMAIL PROTECTED]>
Date: Jul 5, 2005 3:58 PM
Subject: Re: [Tutor] A more Pythonic way to do this
To: "D. Hartley" <[EMAIL PROTECTED]>


I mean an actual group from pygame.sprite either Group or
AbstractGroup. http://www.pygame.org/docs/ref/pygame_sprite.html#Group
Check out the sprite tutorial for more info.



On 7/5/05, D. Hartley <[EMAIL PROTECTED]> wrote:
> Actually, I *have* a holder superclass: but idle is telling me I cant
> iterate over it.  Is this a different kind of group?
> Thanks,
> Denise
> 
> -- Forwarded message --
> From: Adam Bark < [EMAIL PROTECTED]>
> Date: Jul 2, 2005 6:39 AM
> Subject: Re: [Tutor] A more Pythonic way to do this
> To: "D. Hartley" <[EMAIL PROTECTED]> 
> 
> 
> I haven't actually used this myself but if you check the pygame docs
> you should be able to make a group and put all of the sprites in to
> the group. It effectively creates a list of sprites which you will be 
> able to iterate over.
> 
> 
> On 7/2/05, D. Hartley <[EMAIL PROTECTED]> wrote:
> > Also, I'm trying to figure out a way to do the following:
> >
> > If the enemies drop too low, right now it just takes away a life and
> > redraws a screen full of enemies (effectively restarting the level).
> >
> > I'd like to make it so that if they drop too low and you die, it just 
> > takes those ones that you havent killed already and puts them back up
> > in their original starting positions.  I can figure out how to store
> > that "initial position" data, but I dont know how to move the 
> > havent-yet-been-killed sprites back there:
> >
> > what i WANT to do is:
> >
> >   

Re: [Tutor] [pygame] Fwd: A more Pythonic way to do this

2005-07-05 Thread R. Alan Monroe
> should be returning each to its original starting position. Since I
> create initialx/initialy for each enemy when the screen full of
> enemies is drawn (and I know I do create a new initialx/initialy for
> each one - because I had it print the initialx, initialy when the
> screen was drawn and I get 40 sets of values printed for the 40
> enemies on the screen), wouldnt each instance of the Enemy class store
> its own initialx initialy so that when I called
> each.rect.centerx = Enemy.initialx
> each.rect.centery = Enemy.initialy
> .. it would return each to its own starting position?

> Right now, it seems to be printing them all right on top of the other,
> in one enemy position.  At first I thought I was redrawing only one
> enemy, but I shot it, and there seems to be another underneath it. A
> lot of others, actually.  So I can't even see if it is drawing just
> the ones that havent been killed yet or a whole new batch.  And,
> obviously, it's not relocating them correctly :P

Did you inadvertently set the initialx & initialy on a class-wide
basis (within the class's definition), when you meant to set it on a
per-instance basis (within each enemy one at a time)?

Alan

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I sure do love cookies.

2005-07-05 Thread Liam Clarke
Denise - 

Create a cookie, save it, load it as a cookie jar (using cookielib),
create an URLopener using urllib2 that uses the cookiejar, do your
thing. Remember that sending a cookie/receiving a cookie client side is
initiated by the server, so you just have to have the cookie present. 

The technical steps you'll have to puzzle out by reading docs for the
two above mentioned libraries, but it shouldn't take you too long with
the interactive prompt and an open web-browser to get the hang of it. 

Good luck.
On 7/6/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
D. Hartley wrote:> Thank you for the code, everyone.>> I actually have a piece of information (something like> "this+is+a+cookie") that I am trying to *send* (not receive), and I'm
> not sure how to do it.  I looked at the Cookie examples a little bit,> but am having trouble applying what I see there to my present> situation, since there is so much that either a). doesnt apply or b).
> is over my head (usually c). all of the above!). Although the> client-side illustration you provided was very clear and I'll archive> that for future use, too.Did
you see the hint I posted a few days ago? I'll repeat it, if you want
more detail then ask but after all it's supposed to be a challenge :-)What I did was,- create a new cookielib.Cookie- add the cookie to the CookieJar- make a request the same way as when I was collecting cookies
To
create the new Cookie it might help to look at the source for cookielib
(Lib\cookielib.py), the Cookie constructor doesn't seem to be
documented anywhere.To figure out the values for the Cookie constructor it might help to look at one of the cookies you already have.I could be wrong but I don't think Cookie.SimpleCookie is going to get you there.
Kent___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
-- 'There is only one basic human right, and that is to do as you damn well please.And with it comes the only basic human duty, to take the consequences.'
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Case ?

2005-07-05 Thread Liam Clarke
Ah, the cascading broken case statement of doom.
On 7/6/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
On Tue, 5 Jul 2005, Mike Cheponis wrote:> Why does Python not have a "case" statement, like C?Hi Mike,It's a proposed enhancement:
http://www.python.org/peps/pep-0275.htmlThat being said, a dispatch-table approach, using a dictionary, works wellin Python because it's not hard to use functions as values --- most peoplehaven't really missed case/switch statements in Python because dispatch
tables can be very effective.For example, something like this:### C ###switch(state) {case STATE_1: doStateOneStuff();  break;case STATE_2: doStateTwoStuff();
  break;case STATE_3: doStateThreeStuff();  break;default:  doDefaultAction();##has a natural translation into Python as:### Python ###
dispatchTable = { STATE_1: doStateOneStuff,  STATE_2:
doStateTwoStuff,  STATE_3:
doStateThreeStuff }command = dispatchTable.get(state, doDefaultAction)command()##where we're essentially mimicking the jump table that a case/switchstatement produces underneath the surface.
One other consideration about C's case/switch statement is itsbug-proneness: it's all too easy to programmers to accidently forget toput 'break' in appropriate places in there.Hope this helps!
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
-- 'There is only one basic human right, and that is to do as you damn well please.And with it comes the only basic human duty, to take the consequences.'
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor