2017-11-11 56 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':