2017-11-11 6 views
0

数値0-8または 'X'を受け取るまで、新しい入力を要求する関数を作成しています。今まで私はこれを作ったが、うまくいかない。なぜ動作しないのか分かりますが、動作させる方法はわかりません。関数を0-9とします。X

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 

答えて

0

正規表現は、あなたのニーズに最適です:

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 

編集: また、あなたの状態は、仕事ができるが、それは間違っています。次のようにしてください:

while not (ord(field_content) >= ord('0') and ord(field_content) <= ord('8')) and field_content != 'X': 
関連する問題