我的 elif 语句有什么问题:语法无效?

What is wrong with my elif statement: invalid syntax?

class Snake(object):

    def __init__(self, size):

        self.size = size

        self.board = []

        self.snake = []

        self.food = []

        self.score = 0

   def move(self, direction):

if direction in "UP, DOWN, LEFT, RIGHT":

    self.board[self.snake[0]][self.snake[1]] = direction

    self.snake = self.snake[1:] + [self.snake[0]]



def eat(self, food):

if food == "right":

    self.score += 1

elif food == "left":

    self.score -= 1



def checkCollision(self, other):

if self.snake[0] == other.snake[0] and self.snake[1] == other.snake[1]:

    print("Oops, you hit yourself!")

elif self.snake[0] == other.snake[1] and other.snake[0] == self.snake[1]:

    print("Oops, you hit the wall!")

else:

    print("Collision")





if __name__ == "__main__":

    snake = Snake(5)

    print("You are playing as: " + snake.name)

while snake.score >= 0:

    print("You have " + snake.score + " points left.")

    print("moving snake")

    snake.move("left")

    print("Current board:")

    print(snake.board)

    print("Eating food")

    snake.eat("left")

    print("Current board:")

    print(snake.board)

问题出在第 37 行 elif 食物 == "左":

我遇到语法错误:语法无效,我不确定如何解决这个特定错误。我是 python 编程的新手,这对我希望更有经验的人来说应该是显而易见的。对我来说,我似乎无法弄清楚。

您的代码有缩进问题。您可以了解更多信息 .

Python 依赖于其块的缩进。您的多行缩进不正确。

if food == "right":
    self.score += 1
elif food == "left":
    self.score -= 1

确保缩进您的代码。代码的其他部分未正确缩进,例如 checkCollision 和您的 if __name__ == "__main__"

你应该只在 elif food == "left" 中添加表格 使用il和elif的时候这样用(if和elif在space的同一个度数)

if condition:
     do something
elif condition:
     do something