3

Hoping someone can help me with this. I think I need to use the try and except function in order to do what I need but im not creating an error for an exception to occur.

When a user enters a1 it looks at the a1 dictionary and finds an x so it does not satisfy the while loop as true. so it moves to else. I need to reask the question again and start over from the top of the while loop. Is it possible to trigger an exception just because something is false?

here is what I am working with

board = {'a1':'x','a2':'_','a3':'_','b1':'_','b2':'_','b3':'_','c1':' ','c2':' ','c3':' '}


def o_move():
    print 'im over at o now'



def x_move():

    ans = raw_input('Player x please Enter a location: ') #ask user for location
    f = board[ans] #current value of dictionary location selected

    while f is '_' or f is ' ':
        board[ans] == 'x' #writes the user location selected to the dictionary
        o_move() #everything was good, move on
        break #break the loop 
    else:

        print 'space not available Try again'   
        ans = raw_input('Player x please Enter a location: ') #ask again



x_move()
2
  • Does your code work? What is its expected output? What is its actual output?
    – khelwood
    Feb 1, 2016 at 16:15
  • Yes the code works. If the while loop is true then it will write the 'a1' dictionary with an x and move to the next function. basically if the while loop is false i need to reask the question until they pick a directory that is still free. Feb 1, 2016 at 16:18

2 Answers 2

1

A simpler way to do this is to have the function x_move() call itself if a valid move's not chosen the first time. That way, you don't have to write two raw_input() statements.

Here's one way your code might be simplified:

board = {'a1':'x','a2':'_','a3':'_','b1':'_','b2':'_','b3':'_','c1':' ','c2':' ','c3':' '}

def o_move():
    print 'im over at o now'

def x_move():
    ans = raw_input('Player x please Enter a location: ')
    open_positions = ['_', ' ']

    if board[ans] in open_positions:
        board[ans] = 'x'
        o_move()
    else:
        print 'space not available Try again'   
        x_move()

x_move()
0

Instead of having

ans = raw_input('...')

Again, you should just put:

else:
    Print 'space not available, try again'
    x_move()

And that should send it to the start of the while loop again

2
  • WOW! I guess i was over thinking the whole thing. Thank you Feb 1, 2016 at 16:26
  • That should call the method again....not send it to the start of the while loop, dosen't really matter as far as the question is asked again
    – danidee
    Feb 1, 2016 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.