变量在while循环中没有更新,Python

2024-04-18 18:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个战舰游戏。我学习了codecademy的课程,继续我在那里写的游戏,但是我把东西分成了自己的模块并创建了类。一般来说,我对python和编程还是非常陌生的。我以前修过CS课程,现在正在学习EDX上的CS50x

在我的程序中,我再次声明了一个名为play\的变量,并将其设置为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

我真的对这个分手声明有意见。我使用的是Pycharm,在调试器中变量play_again从未设置为0。它在“主菜单”中保持1,我一辈子都搞不懂为什么它没有改变。我觉得这很简单。我觉得这与python中scope的工作方式有关,但是这个变量是在使用它的同一个函数中创建的,所以我不确定为什么两者的作用域会不同。当你进入一个循环时范围会改变吗?你知道吗

谢谢你的帮助!你知道吗


Tags: to声明游戏inputplayif菜单col