代码无限循环运行,我不明白为什么

时间:2020-08-05 02:23:47

标签: python

我觉得在每次循环迭代后,move_spot变量都应重置为值_,但是循环无限运行,而在第一次迭代后不需要用户输入。我看不到错误在哪里,而且对我来说,这更令人困惑,因为第一次迭代可以按我的意愿进行。 (变量和函数都在先前的代码中,但是问题出在该代码块的某个地方,所以我不想发布完整的代码)

while gameOver == False:
    print('\nWhere would you like to move?\nYou can chose top-, mid-, or bot- with L, M, or R at the end')
    move_spot = '_' # I feel like this should reset move_spot every time the loop runs, meaning the user has to give an input
    while move_spot not in theBoard.keys():
        move_spot = input()
    theBoard[move_spot] = userChar
    comp_spot = '_'
    while move_spot not in theBoard.keys():
        comp_spot = random.choice(list(theBoard))
    theBoard[comp_spot] = compChar

    printBoard(theBoard)

1 个答案:

答案 0 :(得分:1)

让我们尝试复制您的代码,并注意更改的行,以便您看到循环行:

while gameOver == False:
       print('\nWhere would you like to move?\nYou can chose top-, mid-, or bot- with L, M, or R at the end')
       move_spot = '_' # I feel like this should reset move_spot every time the loop runs, meaning the user has to give an input
       while move_spot not in theBoard.keys():
           move_spot = input()
       theBoard[move_spot] = userChar
       comp_spot = '_'
       while comp_spot not in theBoard.keys():   # <-- changed this line to comp_spot
           comp_spot = random.choice(list(theBoard))
        theBoard[comp_spot] = compChar

        printBoard(theBoard)

现在看吗?