我正在尝试使用“not”关键字运行 while 循环,但是当我这样做时,循环也接受垃圾值(例如 bjskdjb),这不是 while/for 循环设置的条件.
当我运行 for 循环时,它抛出语法错误。
我在这里犯了什么错误(使用 for 循环和 while 循环)?
我尝试过使用 for 循环和 while 循环来实现。
def askplayerchoice():
playerchoice = ''
while playerchoice not in ('X' , 'O'):
playerchoice = input('Enter X or O: ')
if playerchoice == 'X':
return ['X' , 'O']
else:
return ['O', 'X']
askplayerchoice()
'''
# Using For loop I am getting a syntax error.
def askplayerchoice():
playerchoice = ''
for playerchoice not in ('X' , 'O'):
playerchoice = input('Enter X or O: ')
if playerchoice == 'X':
return ['X' , 'O']
else:
return ['O', 'X']
askplayerchoice()
'''
我希望代码不断要求用户输入“X”或“O”,直到用户输入正确的值。
最佳答案
您可以添加一个 try catch block ,并在输入的字符串与您想要的值不匹配时抛出异常。我已经更新了你的代码。以下是片段:
def askplayerchoice():
playerchoice = ''
while playerchoice.lower() not in ('X' , 'O'):
try:
playerchoice = str(input('Enter X or O: '))
if playerchoice.lower() not in ['x','o']:
raise ValueError('A very specific bad thing happened.')
if playerchoice.lower() == 'x':
return ['X' , 'O']
else:
return ['O', 'X']
except ValueError:
playerchoice = ''
askplayerchoice()
关于python - while 循环在抛出垃圾值时不会重复自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53993274/