python - 如何修复Python中的重复while循环
问题描述
我正在尝试使用 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 循环中的第一个。
解决方案
由于first_player_move
不改变为false
,当内部循环结束时,外部开始一个新的循环并再次调用内部。
顺序流是:
- 进入第一个循环 =>
True
#如此真实 - 进入内循环 =>
first_player_move
isTrue
# so true 然后执行内部块
breaks
并进入第一个循环并重复上述步骤进入第一个循环 =>
True
#如此真实- 进入内循环 =>
first_player_move
isTrue
# so true
推荐阅读
- java - 使用 Hibernate 更新 HSQLDB 上的 LOB/BLOB 值会产生数据异常
- r - 使用 summarise_all 折叠多个字符列会引发错误或包含 NA
- linux - 如何在 nohup 模式下解压文件
- json - “Book []”类型上不存在属性“ResultJson”
- ruby - 如何拆分 Ruby 哈希数组
- android - 将位图保存到 SD 卡不创建任何文件
- c++ - 使用 new 运算符初始化指向 const float 等的指针的指针
- highcharts - Highcharts如何在柱形图中显示顶线?
- jquery - 如何使用 jquery.transit 使侧边栏进入视图并保持在顶部
- hibernate - 未找到从 JNDI 检索的 DataSource 的驱动程序