0

I'm making a function that will keep asking for a new input until it receives either numbers 0-8 or 'X'. So far I made this, but it doesn't work. I know why it doesn't work, but don't know how to make it work.

def get_computer_choice_result(computer_square_choice):
    print('What is hidden beneath square', computer_square_choice, '? (0 - 8 -> number of surrounding mines or X)')
    field_content = input()
    while not (ord(field_content) > ord('0') and ord(field_content) < ord('8')) or field_content != 'X':
        field_content = input('Invalid input.Please enter either 0 - 8 -> number of surrounding mines, or X -> a mine.')
    return field_content
slackmart
  • 4,754
  • 3
  • 25
  • 39
Wranny
  • 11
  • 4

1 Answers1

0

Regular expressions are perfect for your needs:

import re

def get_computer_choice_result(computer_square_choice): 
    print('What is hidden beneath square', computer_square_choice, '? (0 - 8 -> number of surrounding mines or X)') 
    field_content = input() 
    while not re.match(r"([0-8]|X)$", field_content):
        field_content = input('Invalid input.Please enter either 0 - 8 -> number of surrounding mines, or X -> a mine.') 
    return field_content

Edit: Also, your condition could work but it is wrong. It should be the following:

while not (ord(field_content) >= ord('0') and ord(field_content) <= ord('8')) and field_content != 'X':
RomainTT
  • 140
  • 5