《Python编程快速上手》4.10 实践项目

4.10.1 逗号代码

1
2
3
4
5
6
7
8
9
10
def strlist(listname):
spam = listname[0]
for i in range(1, len(listname) - 1):
spam = spam + ', ' + str(listname[i])
spam = spam + ' and ' + str(listname[len(listname) - 1])
return spam

spam = ['apples', 'bananas', 'tofu', 'cats']
example = strlist(spam)
example
输出
1
'apples, bananas, tofu and cats'

4.10.2 字符图网格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]

for a in range(6):
for b in range(9):
print(grid[b][a], end = '')
print('\n')
输出
1
2
3
4
5
6
7
8
9
10
11
..OO.OO..

.OOOOOOO.

.OOOOOOO.

..OOOOO..

...OOO...

....O....