4.1 for循环语句
# encoding=utf-8
magicians = ['jun', 'bin', 'qi', 'feng']
for magician in magicians:
print('welcome ' + magician.title())
print(magician + ",that was a great trick")
# 虽然不推荐,但人家确实活着
print("game end")
print("变量仍然活着:" + magician)
welcome Jun
jun,that was a great trick
welcome Bin
bin,that was a great trick
welcome Qi
qi,that was a great trick
welcome Feng
feng,that was a great trick
game end
变量仍然活着:feng
4.2关于python的缩进认知:
Python根据缩进判断代码行之间的关系.这点与java完全不同
在代码行for magician in magicians:后面,每个缩进的代码行都是循环的一部分.而不属于循环部分的代码请不要缩进.
4.3创建数值列表
range()函数可以生成一系列数字,也可以调整步长,左闭右开
list()函数
max()
min()
sum()
# encoding=utf-8
# 左闭右开
for value in range(1, 5):
print(value)
# 可以指定步长
for value in range(2, 20, 2):
print(value)
numbers = range(1, 10)
print(numbers)
print(list(numbers))
suquares = []
suquares = list()
for value in range(1, 11):
suquares.append(value ** 2)
print(suquares)
digits = [1, 2, 3, 4, 5, 6]
print(min(digits))
print(max(digits))
print(sum(digits))
print(min(1, 3, 5, 6))
# 列表解析:一行代码生成平方数列表
suquares = [value ** 2 for value in range(1, 11)]
print(suquares)
1
2
3
4
2
4
6
8
10
12
14
16
18
range(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
1
6
21
1
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
4.4.1切片
创建切片,可指定要使用的第一个元素和最后一个元素的索引。左闭右开。
切片是列表的副本,不修改原始列表。
复制整个列表
>>>players[:]
# encoding=utf-8
players = ['zhang san', 'li si ', 'wang wu', 'zhao liu']
# 获取前两名队员
print(players[0:2])
# 默认从开头开始
print(players[:3])
# 默认到结尾结束
print(players[2:])
print(players[:-1])
print('last 3 players:' + str(players[-3:]))
# 遍历切片
for player in players[:3]:
print(player)
# 利用列表切片复制整个列表
my_players = players[:]
my_players.append("qian qi")
print('---------=====--------')
for my_player in my_players:
print(my_player)
print('---------=====--------')
for player in players:
print(player)
['zhang san', 'li si ']
['zhang san', 'li si ', 'wang wu']
['wang wu', 'zhao liu']
['zhang san', 'li si ', 'wang wu']
last 3 players:['li si ', 'wang wu', 'zhao liu']
zhang san
li si
wang wu
---------=====--------
zhang san
li si
wang wu
zhao liu
qian qi
---------=====--------
zhang san
li si
wang wu
zhao liu
4.5元组
python把不能修改的值成为不可变的,而不可变的列表成为元组。
不能修改元组里的元素,但可以给元组变量重新赋值一个新的元组
# encoding=utf-8
# 元组
dimensions = (80, 200, 500)
print(dimensions)
print(dimensions[0])
print(dimensions[1])
# TypeError: 'tuple' object does not support item assignment
# dimensions[0] = 40
# 修改元组变量,可以给整个变量重新赋值
dimensions = (800, 200, 500, 600)
print(dimensions)
(80, 200, 500)
80
200
(800, 200, 500, 600)
4.6
PEP8(Python Enhancement Proposal) Python改进提案,为python程序员提供了代码格式设置指南。