英文:
Why does my variable (winning) not get reassigned when I try to reassign it?
问题
def winningcheck(board):
winning = ''
if board[1] == board[2] == board[3]:
print('游戏已经获胜')
winning = 'True'
else:
print('游戏尚未获胜')
test = ['#', 'X', 'X', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
winningcheck(test)
print(winning)
英文:
def winningcheck(board):
winning == ''
if board[1] == board[2] == board[3]:
print('The game has been won')
winning == 'True'
else:
print('The game has not been won')
test = ['#', 'X ', 'X ', 'X ', ' ', ' ', ' ', ' ', ' ', ' ']
winningcheck(test)
print(winning)
I'm a beginner, but I expected the variable winning to be reassigned to 'true' when the 'if' condition was met. However, it just returns an empty string instead when I try to print the variable.
答案1
得分: 1
你在代码中使用了winning==
而不是winning='True'
,这是一个条件判断而不是赋值操作。
另外,你需要将winning
声明为全局变量,就像我所示范的那样,否则函数外部的代码无法访问它。
winning = ''
def winningcheck(board):
global winning
if board[1] == board[2] == board[3]:
print('游戏已经赢了')
winning = 'True'
else:
print('游戏尚未赢得')
test = ['#', 'X ', 'X ', 'X ', ' ', ' ', ' ', ' ', ' ', ' ']
winningcheck(test)
print(winning)
但是,你应该使用布尔变量来表示winning
,而不是字符串,因为这更有效率,也更符合你的意图。
所以你应该初始化winning = False
,然后使用winning = True
来修改它。
英文:
You did winning==
instead of winning='True'
, this was a condition and not an assignment.<br>
Additionally you need to make winning a global variable as I've shown. otherwise the code outisde the function can't access it.
winning = ''
def winningcheck(board):
global winning
if board[1] == board[2] == board[3]:
print('The game has been won')
winning = 'True'
else:
print('The game has not been won')
test = ['#', 'X ', 'X ', 'X ', ' ', ' ', ' ', ' ', ' ', ' ']
winningcheck(test)
print(winning)
But you should use a boolean variable for winning
instead of a string, as its more efficient and it serves the intended use for you.<br>
So you would init winning = False
and change with winning = True
.
答案2
得分: 0
Comparison:
winning == 'True'
Assignment:
winning = True
注意不同数量的 "=" 符号。
英文:
Comparison:
winning == 'True'
Assignment:
winning = True
Note the different number of "=".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论