为什么当我尝试重新分配它时,我的变量(winning)没有被重新分配?

huangapple go评论74阅读模式
英文:

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=&#39;True&#39;, 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 = &#39;&#39;
def winningcheck(board):
    global winning
    if board[1] == board[2] == board[3]: 
        
        print(&#39;The game has been won&#39;)
        
        winning = &#39;True&#39;
        
    else:
        print(&#39;The game has not been won&#39;)
        

test = [&#39;#&#39;, &#39;X &#39;, &#39;X &#39;, &#39;X &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;]

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 == &#39;True&#39;

Assignment:

winning = True

Note the different number of "=".

huangapple
  • 本文由 发表于 2023年7月23日 17:57:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定