-1

I'm trying to make a TicTacToe game, and I do have a basically working prototype, managed to convert it to an exe file and so forth, but I'm going back and trying to create a condition that the input must be a valid option or else an error message is popped up and the p1 function restarted. How do I have python check if the input matches any one item on a list?

Ignore the globals, they haven't got anything to do with problem, they're for the board.

def p1():
    global top
    global a1
    global a2
    global a3
    global b1
    global b2
    global b3
    global c1
    global c2
    global c3
    print()
    print('Player One, it is your move')
    x = input()
        if str(x) == any('a1','A1','a2','A2','a3','A3','b1','B2','b3','B3','c1','C1','c2','C2','c3','C3'):
            # A lot of code goes here
    elif x == 'restart':
        begin()
    else:
        print('Invalid Command')
        print()
        p1()
Jack Cotting
  • 45
  • 2
  • 8

1 Answers1

2

Use in:

if x in ('a1','A1','a2','A2','a3','A3','b1','B2','b3','B3','c1','C1','c2','C2','c3','C3')

This will check that value stored in x variable is among elements of the tuple.

warvariuc
  • 57,116
  • 41
  • 173
  • 227
  • Does what was asked, but is it not easier to test the first and second character against bounds? – Jongware Jun 20 '15 at 11:36
  • 1
    Maybe it is easier and there are better ways, but looks like the author does not know Python/programming well enough yet for advanced topics. – warvariuc Jun 20 '15 at 11:37
  • @warvariuc yeah I'm still getting a hang of the basics, hence the TicTacToe. – Jack Cotting Jun 20 '15 at 11:44
  • Is that approach so advanced, or just not "Pythonic"? (Fun fact: I wrote my first Python program yesterday and used `in` without thinking too much about it. I noted that down as "well that seems to work as I thought it would" - and didn't think too much of it.) – Jongware Jun 20 '15 at 11:44
  • 1
    @Jongware looks like you have programming experience. But from what I see in the code, the author does not. IMO, it doesn't help people to show them the correct way, they learn better when they understand themselves, from their own experience. A good student will improve his program continuously, sometimes rewrite the program from scratch. It's an iterative process. – warvariuc Jun 20 '15 at 11:53
  • @Jongware > I noted that down as "well that seems to work as I thought it would" - and didn't think too much of it. < That's what I like about Python. Most of the programs in Python do what they seem to be doing. It was the only language that my program worked immediately in. – warvariuc Jun 20 '15 at 11:57
  • 1
    Yes! That's what I indeed found when [writing this](http://stackoverflow.com/a/30926976/2564301). I had a clear idea of the algorithm to use, and (except for the colons) Python Did What I Wanted. I had way more problems with the API documentation of Sublime. – Jongware Jun 20 '15 at 12:02