python battleship_Python 入门教程 12 ---- Battleship!-阿里云开发者社区
第一節(jié)
1 介紹了list的一種方法board.append(["O"] * 5),是把'O'這個(gè)元素復(fù)制5遍
2 練習(xí):利用這個(gè)方法,使得空列表board為一個(gè)5*5的矩陣,元素值為O
board = []
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
第二節(jié)
1 通過第一節(jié)的學(xué)習(xí)我們知道,5*5的矩陣就是一個(gè)二維的列表
2 我們可以通過for循環(huán)來打印二維列表的每一行
3 練習(xí):通過for循環(huán)把二維列表的每一行打印出來
board = []
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
def print_board(board):
for row in board:
print row;
第三節(jié)
1 介紹了Python中的一種方法join
2 join方法用來連接字符串,比如
li = ['my','name','is','bob']
print ' '.join(li)
>>'my name is bob'
3 練習(xí):把第二節(jié)中的board二維列表中的每一行,利用join方法使得每一個(gè)O之間都有一個(gè)空格
board = []
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
def print_board(board):
for row in board:
print " ".join(row)
第四節(jié)
1 首先介紹了Python中產(chǎn)生一個(gè)隨機(jī)數(shù)的方法,我們必須要從random里面導(dǎo)出randint,然后利用randint(x,y)產(chǎn)生[x,y]之間的隨機(jī)數(shù)
# generate a random integer between x and y
from random import randint
randint(x , y)
2 練習(xí):利用randint(x,y)方法隨機(jī)產(chǎn)生兩個(gè)行和列的下標(biāo),并且這兩個(gè)值要小于行和列的長(zhǎng)度
# generate a random integer between x and y
from random import randint
board = []
for x in range(0, 5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
# Add your code below!
def random_row(board):
x = randint(0 , len(board)-1)
return x
def random_col(board):
x = randint(0 , len(board)-1)
return x
第五節(jié)
1 首先回顧了Python的方法raw_input(),用來表示標(biāo)準(zhǔn)的輸入,但是返回的值都是認(rèn)為是字符串
2 接著介紹了Python的另外一個(gè)函數(shù)int(),表示把值強(qiáng)制轉(zhuǎn)化為整數(shù),比如int(raw_input())就是把輸出的字符串轉(zhuǎn)化成整數(shù)
3 練習(xí):利用int()和raw_input()函數(shù)得到兩個(gè)數(shù),保存到變量ship_row和ship_col中
from random import randint
board = []
for x in range(0,5):
board.append(["O"] * 5)
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[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
# Add your code below!
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
總結(jié)
以上是生活随笔為你收集整理的python battleship_Python 入门教程 12 ---- Battleship!-阿里云开发者社区的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 灌区农业水价综合改革解决方案
- 下一篇: 2012-07《信息资源管理 02378