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

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

Why does my variable (winning) not get reassigned when I try to reassign it?

问题

  1. def winningcheck(board):
  2. winning = ''
  3. if board[1] == board[2] == board[3]:
  4. print('游戏已经获胜')
  5. winning = 'True'
  6. else:
  7. print('游戏尚未获胜')
  8. test = ['#', 'X', 'X', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
  9. winningcheck(test)
  10. print(winning)
英文:
  1. def winningcheck(board):
  2. winning == ''
  3. if board[1] == board[2] == board[3]:
  4. print('The game has been won')
  5. winning == 'True'
  6. else:
  7. print('The game has not been won')
  8. test = ['#', 'X ', 'X ', 'X ', ' ', ' ', ' ', ' ', ' ', ' ']
  9. winningcheck(test)
  10. 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声明为全局变量,就像我所示范的那样,否则函数外部的代码无法访问它。

  1. winning = ''
  2. def winningcheck(board):
  3. global winning
  4. if board[1] == board[2] == board[3]:
  5. print('游戏已经赢了')
  6. winning = 'True'
  7. else:
  8. print('游戏尚未赢得')
  9. test = ['#', 'X ', 'X ', 'X ', ' ', ' ', ' ', ' ', ' ', ' ']
  10. winningcheck(test)
  11. 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.

  1. winning = &#39;&#39;
  2. def winningcheck(board):
  3. global winning
  4. if board[1] == board[2] == board[3]:
  5. print(&#39;The game has been won&#39;)
  6. winning = &#39;True&#39;
  7. else:
  8. print(&#39;The game has not been won&#39;)
  9. test = [&#39;#&#39;, &#39;X &#39;, &#39;X &#39;, &#39;X &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;]
  10. winningcheck(test)
  11. 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:

  1. winning == 'True'

Assignment:

  1. winning = True

注意不同数量的 "=" 符号。

英文:

Comparison:

  1. winning == &#39;True&#39;

Assignment:

  1. 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:

确定