首页 > 解决方案 > 变量在while循环中不更新,python

问题描述

我正在尝试编写战舰游戏。我学习了关于 codecademy 的课程并继续我在那里编写的游戏,但我将它们分成了它们自己的模块并创建了类。总的来说,我对 python 和编程还是很陌生。我以前参加过 CS 课程,现在正在 EDX 上学习 CS50x

在我的程序中,我声明了一个名为 play_again 的变量并将其设置为 0。然后我使用 while 语句运行我的游戏while play_again != 2:

这本质上是我的游戏“主菜单”。

play_again = 0

while play_again != 2:

    if play_again == 0:
        print("Would you like to play a game of Battleship?")
        print("Enter 1 to play")
        print("Enter 2 to exit")
        play_again = int(input("Make a selection: "))

    if play_again == 1:

这个块是我遇到问题的地方,它嵌套在if上面的块中,在其他一些代码之后,这些代码只是创建了一个游戏板和一个要查找的船。

        for turn in range(4):
            print("Turn: ", turn + 1)
            guess_row = int(input("Guess Row: ")) - 1 # the "-1"s here 
compensate for our count starting at 0
            guess_col = int(input("Guess Col: ")) - 1

            #checks to see if the users guess is correct
            if guess_row == ship_row and guess_col == ship_col:
                print("Congratulations! You sank my battleship!")
                play_again == 0
                break

我真的对这个 break 语句有疑问。我正在使用 Pycharm 并且在调试器中该变量play_again永远不会设置为 0。它在“主菜单”中保持为 1,我无法终生弄清楚为什么它没有改变。我觉得它超级简单。我觉得这与作用域在 python 中的工作方式有关,但是变量是在它使用的同一个函数中创建的,所以我不确定为什么两者之间的作用域会不同。进入循环时范围会改变吗?

感谢您的任何帮助!

标签: pythonloopswhile-loopscopebreak

解决方案


play_again == 0可能打算键入play_again = 0.


推荐阅读