【发布时间】:2019-07-05 03:08:20
【问题描述】:
我正在尝试使用 while 循环在两个用户之间交替轮流,但我的代码卡在“while first_player_move is True:”循环中。我怎样才能解决这个问题,让我的 while 循环遍历两个玩家的回合。
我尝试在不同的地方添加“继续”和“中断”,并尝试向上切换布尔值,但似乎没有任何效果。
word_fragment = ''
first_player_move = True
while True:
while first_player_move is True:
added_letter = input('Which single letter would you like to add to the fragment? ')
word_fragment += added_letter
print('The current word fragment is: ' + word_fragment)
print('It is now ' + player2_name + "'s turn.")
if word_fragment in open('data.txt').read() and len(word_fragment) > 3:
print('I am sorry, you just lost. ' + player2_name + ' is the winner!')
# call a function to end the game
break
while first_player_move is False:
added_letter = input('Which single letter would you like to add to the fragment? ')
word_fragment += added_letter
print('The current word fragment is: ' + word_fragment)
print('It is now ' + player1_name + "'s turn.")
if word_fragment in open('data.txt').read() and len(word_fragment) > 3 :
print('I am sorry, you just lost. ' + player1_name + ' is the winner!')
# call a function to end the game
break
我希望输出贯穿每个玩家的回合并最终打印“现在是'下一个玩家'的回合”,但它会继续为下一个玩家回合打印相同的名称,这告诉我代码卡在两个 while 循环中的第一个。
【问题讨论】:
-
使用
if代替while并将first_player_move重置为false -
成功了,非常感谢!
-
关于
is True的一些东西:起初绝对不需要,如果你有布尔值if(或while)条件在if p:上的行为与@987654330 上的行为相同@。许多 Python 函数返回“真实”对象,这些对象被认为是真实的 (bool(p) == True),但不完全是True。对于这样的对象,is True将失败。最后但并非最不重要的一点是is运算符正在测试双方是否是完全相同的对象。仅因为 CPython 解释器中的优化,这适用于您的情况。使用==比较值!
标签: python python-3.x while-loop