我正在制作一个功能,在收到0-8或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 :(得分: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':