Python缩进(制表符/间距错误)

时间:2015-10-05 02:49:20

标签: python indentation

我已经通过Python制作了一个'战舰'程序,并决定构建我的代码(因为之前它很乱,但工作正常)。但是每当我运行我的代码时,它现在会弹出一个缩进错误:

"File "python", line 29
guess_col = int(raw_input("Guess Col:"))
IndentationError: unindent does not match any outer indentation level"

我四处搜索并意识到我已经使用了一些空格以及标签,所以我将它纯粹切换到标签(缩进4个空格)。但问题仍然存在,我不明白为什么。有人能够分享为什么会这样吗?

from random import randint
board = []
turn = 0
def print_board(board):
   for row in board:
       print " ".join(row)
def random_row(board):
    return randint(0, len(board) - 1)
def random_col(board):
    return randint(0, len(board) - 1)

#Start Battleship Functionality Here
print "Let's play Battleship!"
for x in range(5):
    board.append(["O"] * 5)
    print_board(board)

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col


for turn in range(4):
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
    print "Oops, that's not even in the ocean."
    print "Turn", turn + 1
elif (board[guess_row][guess_col] == "X"):
    print "You guessed that one already."
    print "Turn", turn + 1
elif guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sunk my battleship!"
    print_board(board)
    break
elif turn == 3:
    print "Game Over"
else:
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
    print "Turn", turn + 1
    print_board(board)

1 个答案:

答案 0 :(得分:0)

问题出在For语句中 - 因为我的IF在for循环下没有正确缩进,缩进级别不匹配。对此进行更正导致程序顺利运行。

    for turn in range(4):
        guess_row = int(raw_input("Guess Row:"))
        guess_col = int(raw_input("Guess Col:"))

        if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
            print "Oops, that's not even in the ocean."
            print "Turn", turn + 1
            etc....

感谢大家的投入!