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

Matt Smith matt at mattanddawn.orangehome.co.uk
Mon Nov 12 21:11:52 CET 2007

Hi there,

I am currently working on a noughts and crosses program to try and teach 
myself some very simple AI programming and also to start to use OOP in 

I am currently writing the framework for the game so I can then write a 
number of functions or a class to deal with the strategy side of things.

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.

I currently have the following code.

while 1:
         xpos = input ("Where do you want to go? ")
     except cantgo:
         print "You can't go there!"

which calls the following method:

     def addx(self,pos):
         if pos in range(1,10) and self.state[pos-1] == "":
             self.state[pos-1] = "X"
             raise cantgo

The cells of the game are referenced by the numbers 1 to 9. The code 
gave the following error:

Traceback (most recent call last):
   File "noughts_and_crosses.py", line 49, in <module>
     except cantgo:
NameError: name 'cantgo' is not defined

Interesting the first pass of the code above did not return an error but 
the second pass did. Currently I have the same code twice for X's and 
O's. Next, I defined the error using:

cantgo = "can't go"

And now I get:

noughts_and_crosses.py:33: DeprecationWarning: raising a string 
exception is deprecated
   raise cantgo
You can't go there!

But the program will not let me enter any (valid) move at all now. This 
looks like it is not breaking out of the while loop correctly, which, 
when I look back at my code, is to be expected.

Is there a typical 'Pythonic' way of dealing with this situation.

More information about the Tutor mailing list