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 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)
(缩进不准确)
答案 0 :(得分:0)
turn
一次获取range(4)
中的值。例如:
for turn in range(4):
print turn
0
1
2
3
此行为称为对序列的迭代,这意味着for
语句迭代或连续地按range(4)
中的每个元素按照它们出现在该序列中的顺序并分配它变量turn
。 https://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]