代码学院不明白

时间:2015-09-10 19:55:21

标签: python function

for turn in range(4):
    print "Turn", turn + 1

这里定义了转弯。不知何故,程序打印转1转2等等.....每次。但转弯从未定义过。请帮忙

这是完整的参考代码

from random import randint

board = []

for x in range(5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print "Let's play Battleship!"
print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

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

此处的所有内容都应该在你的for循环中进行!

请务必缩进四个空格!

for turn in range(4):
    print "Turn", turn + 1


    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))

     if guess_row == ship_row and guess_col == ship_col:
         print "Congratulations! You sunk my battleship!"
    else:
    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."
    elif(board[guess_row][guess_col] == "X"):
        print "You guessed that one already."
    else:
        print "You missed my battleship!"
        board[guess_row][guess_col] = "X"
    # Print (turn + 1) here!
    print_board(board)

(缩进不准确)

1 个答案:

答案 0 :(得分:0)

turn一次获取range(4)中的值。例如:

for turn in range(4):
    print turn
0
1
2
3

此行为称为对序列的迭代,这意味着for语句迭代或连续地按range(4)中的每个元素按照它们出现在该序列中的顺序并分配它变量turnhttps://docs.python.org/2/tutorial/controlflow.html#for-statements记录了for个语句。

range(4)是列表[0, 1, 2, 3],可以演示如下:

a = range(4)
print a
[0, 1, 2, 3]