Python 为什么,尽管实现了';如果';条件,这个break语句不是结束循环吗?
我正在从一本教程书中用python制作一个石头剪刀游戏。我想我是在不折不扣地照本宣科,但出于某种原因,这种“休息”的说法不起作用Python 为什么,尽管实现了';如果';条件,这个break语句不是结束循环吗?,python,break,Python,Break,我正在从一本教程书中用python制作一个石头剪刀游戏。我想我是在不折不扣地照本宣科,但出于某种原因,这种“休息”的说法不起作用 while True: # Main game loop print('%s Wins, %s Losses, %s Ties' %(wins,losses,ties)) while True: # Player input loop print('Enter your move: (r)ock (p)aper (s)cissors
while True: # Main game loop
print('%s Wins, %s Losses, %s Ties' %(wins,losses,ties))
while True: # Player input loop
print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit')
playerMove = input()
if playerMove== 'q':
sys.exit() # Quit the program
if playerMove == 'r' or playerMove =='p' or playerMove =='s':
print('at least this is working')
break # Break out of player input loop
print('but this is not')
# Display player move
if playerMove == 'r':
print('ROCK versus...')
elif playerMove == 'p':
代码还在继续,但这就是与此问题相关的全部内容。当我运行它时,它显示如下
ROCK,PAPER,SCISSORS
0 Wins, 0 Losses, 0 Ties
Enter your move: (r)ock (p)aper (s)cissors or (q)uit
r
at least this is working
0 Wins, 0 Losses, 0 Ties
Enter your move: (r)ock (p)aper (s)cissors or (q)uit
“q”表示退出选项工作得很好,因此它显然得到了输入。除此之外,它只是不断重复循环。
正如你们所看到的,我在那个里放了一些文字,只是为了实验,并显示出事情在哪里发生了变化
我做错了什么?语句将带您脱离最内部的循环,而不是“主”外部循环。最好将内部循环更改为以下内容:
input_loop = True
while input_loop: # Player input loop
print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit')
playerMove = input()
if playerMove== 'q':
sys.exit() # Quit the program
if playerMove == 'r' or playerMove =='p' or playerMove =='s':
print('at least this is working')
input_loop = False # Break out of player input loop
print('but this is not')
break
语句将使您脱离最内部的循环,而不是“main”外部循环。最好将内部循环更改为以下内容:
input_loop = True
while input_loop: # Player input loop
print('Enter your move: (r)ock (p)aper (s)cissors or (q)uit')
playerMove = input()
if playerMove== 'q':
sys.exit() # Quit the program
if playerMove == 'r' or playerMove =='p' or playerMove =='s':
print('at least this is working')
input_loop = False # Break out of player input loop
print('but this is not')
您有两个嵌套循环。如果您跳出第一个循环,您将立即重新输入它,因为您不会跳出第二个循环。我会将第一个循环改为,而不是在True时说
,在玩时说,并在游戏结束时将playing设置为False。您有两个嵌套循环。如果您跳出第一个循环,您将立即重新输入它,因为您不会跳出第二个循环。我会将第一个循环改为,而不是在True时说,在玩
时说,并在游戏结束时将playing设置为False。正如其他人已经告诉您的,您已经嵌套了两个循环。break
语句只能使您脱离内部循环,但您希望脱离外部循环。关于如何解决这个问题,可以找到很多答案。正如其他人已经告诉您的,您已经嵌套了两个循环。break
语句只能使您脱离内部循环,但您希望脱离外部循环。关于如何解决这个问题,可以找到很多答案。我现在已经解决了这个问题
最初的原因是
print('but this is not')
没有打印是因为我已经打破了while循环
下面的代码没有从#Display player move
部分开始运行的原因是缩进。程序的其余部分与#播放器输入循环
处于相同的缩进级别,因此一旦该循环被打破就被忽略
我把剩下的代码移到了一个缩进级别上,程序现在运行得很好我现在已经解决了这个问题
最初的原因是
print('but this is not')
没有打印是因为我已经打破了while循环
下面的代码没有从#Display player move
部分开始运行的原因是缩进。程序的其余部分与#播放器输入循环
处于相同的缩进级别,因此一旦该循环被打破就被忽略
我把剩下的代码移到了一个缩进级别上,程序现在可以正常运行了您希望中断主游戏循环吗?break
只退出最近的循环,而不是所有循环。它甚至在你的代码的注释中这样说:“打断#打断玩家输入循环”
你希望打断游戏主循环吗?break
只退出最近的循环,而不是所有循环。它甚至在你的代码的注释中这样说“中断#中断播放器输入循环”