为什么,尽管满足“if”标准,这个 break 语句并没有结束循环?

时间:2021-01-23 23:22:45

标签: 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 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' 工作得很好,所以它很清楚地得到了输入。除此之外,它只是不断重复循环。 正如你所看到的,我在里面放了一些文字,只是为了试验并展示哪里出现了问题。

我在这里做错了什么?

4 个答案:

答案 0 :(得分:3)

break 语句将带您离开最内层循环,而不是“主”外层循环。最好将内部循环更改为如下所示:

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')

答案 1 :(得分:2)

您有两个嵌套循环。如果你跳出第一个循环,你会立即重新进入它,因为你没有跳出第二个循环。我会将第一个循环改为而不是说 while True,而是说 while playing,并在游戏结束时将 play 设置为 False。

答案 2 :(得分:2)

正如其他人已经告诉您的那样,您嵌套了两个循环。 break 语句只会让您脱离内循环,但您想要脱离外循环。可以在here找到很多关于如何解决这个问题的答案。

答案 3 :(得分:0)

我现在已经解决了这个问题,

最初的原因

        print('but this is not')

没有打印是因为我已经打破了那个while循环。

以下代码没有从 # Display player move 部分开始运行的原因是缩进。它以及程序的其余部分与 # Player input loop 处于相同的缩进级别,因此一旦该循环被破坏,就会被忽略。

我将其余代码移到一个缩进级别,程序现在可以正常工作