【发布时间】:2019-08-01 01:15:56
【问题描述】:
我通过使用 Python 中的字典来制作一个简单的井字游戏,来自用 Python 自动化无聊的东西。当条件匹配时,while 循环应该中断。但它一直在继续。
我尝试用“or”替换“and”运算符,第一次运行时循环中断。它出什么问题了?为什么条件满足循环不中断?
theBoards = {'A' : ' ', 'B': ' ', 'C' : ' ',
'D' : ' ', 'E' : ' ', 'F' : ' ',
'G' : ' ', 'H': ' ', 'I': ' '}
def drawBoard(theBoard):
print(theBoard['A'] + '|' + theBoard['B'] + '|' + theBoard['C'])
print('-+-+-')
print(theBoard['D'] + '|' + theBoard['E'] + '|' + theBoard['F'])
print('-+-+-')
print(theBoard['G'] + '|' + theBoard['H'] + '|' + theBoard['I'])
drawBoard(theBoards)
turn = 'X'
while True:
move = input("Where do you want your " + turn + ': ')
theBoards[move] = turn
drawBoard(theBoards)
if( theBoards['A'] == theBoards['B'] == theBoards['C']
and theBoards['D'] == theBoards['E'] == theBoards['F']
and theBoards['G'] == theBoards['H'] == theBoards['I']
and theBoards['A'] == theBoards['D'] == theBoards['G']
and theBoards['B'] == theBoards['E'] == theBoards['H']
and theBoards['C'] == theBoards['F'] == theBoards['I']
and theBoards['A'] == theBoards['E'] == theBoards['I']
and theBoards['C'] == theBoards['E'] == theBoards['G']):
print("Winner is " + turn)
break
if turn == 'X':
turn = 'O'
else:
turn = 'X'
【问题讨论】:
-
你应该使用
or。您不希望所有这些条件都是True。但是,大多数条件将在第一步之后满足,因为除了一个位置之外,所有位置都是' '。
标签: python