[Tutor] How to keep trying something until it doesn't return an error?

wesley chun wescpy at gmail.com
Mon Nov 12 23:30:18 CET 2007

i won't have time to elaborate on everything here... i'll let the
other smart tutors on the list do that, but i'll give some short
snippets of advice down below....

> I'm stuck trying to write a method which will only accept a legal move
> and will keep asking until it gets a legal answer. I can see that
> working out how to do this efficiently will be very useful in my future
> programming as well.
> while 1:

you can use True/False for 1/0 now in Python.

>      try:
>          xpos = input ("Where do you want to go? ")

try to avoid use of input()... stick with raw_input() as it is less "dangerous."

>          gameboard.addx(xpos)
>          gameboard.draw()
>          break
>      except cantgo:
>          print "You can't go there!"

based on the this code plus that of addx() which you defined, you can
probably do this entire excercise without using exceptions at all...
it will help simplify things in this situation where exceptions are
not necessarily called for.

> cantgo = "can't go"
> And now I get:
> noughts_and_crosses.py:33: DeprecationWarning: raising a string
> exception is deprecated
>    raise cantgo

the reason why this is the case  is because exceptions used to be
strings but now are required to be classes.  if you really want to use
exceptions, you need to create something like:

class CantGoError(Exception):

hope this helps, if only a little!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca

More information about the Tutor mailing list