0x0B while循环
- 正常的循环
>>> i = 1 >>> while i <= 5: ... print(i) ... i +=1 ... 1 2 3 4 5
- 死循环
>>> while 1 == 1: ... print("good") ... good good good good good good good good
>>> while True: ... print("good") ... good good good good good good good good
- break跳出循环
➜ python cat test2.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- i = 1 while 1 == 1: print(i) i = i+1 if i >= 5: print('Breaking') break print('Finished')
➜ python ./test2.py 1 2 3 4 Breaking Finished
- continue 跳回本次循环而不退出
➜ test cat test2.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- i = 0 while True: i = i+1 if i == 2: print('Skiping 2') continue if i >= 5: print('Breaking') break print(i) print('Finished')
➜ test ./test2.py 1 Skiping 2 3 4 Breaking Finished
0x0C 列表 []
- 列表中的元素从0开始计数,下例中的words是列表的名字,[]中的内容标识的是元素的位置
>>> words = ['abc','bcd','!'] >>> print(worlds[0]) abc >>> print(worlds[1]) bcd >>> print(worlds[2]) !
- 空的列表用[]来创建
>>> words = [] >>> print(words) []
- 列表里面可以还有列表
>>> nums = 3 >>> things = ['string',0,[1,2,nums],4.56] >>> print(things[1]) 0 >>> print(things[2]) [1, 2, 3] >>> print(things[2][2]) 3 ***
- str可以当作列表来使用,如果用int会引发TypeError
>>> str = "Hello world!" >>> print(str[8]) r
>>> str = 123 >>> print(str[0]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not subscriptable
- 元素替换
>>> nums = [7,7,7,7,7] >>> nums[2] = 5 >>> print(nums) [7, 7, 5, 7, 7]
- 元素 *操作
>>> nums = [1,2,3] >>> print(nums + [4,5,6]) [1, 2, 3, 4, 5, 6]
>>> print(nums * 3) [1, 2, 3, 1, 2, 3, 1, 2, 3]
- 元素布尔
>>> words = ['eggs','spam','sausage','good'] >>> print('egg' in words) False >>> print('eggs' in words) True >>> print('good' in words) True
- 支持not操作
>>> nums = [1,2,3] >>> print(not 4 in nums) True >>> print(4 not in nums) True
>>> print(not 3 in nums) False >>> print(3 not in nums) False
0x0D range
- range 默认从0开始,范围-1
>>> numbers = list(range(10)) >>> print(numbers) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- 从这个例子可以看出,实际上是从前一个参数开始,最大数-1
>>> numbers = list(range(3,8)) >>> print(numbers) [3, 4, 5, 6, 7]
- 第三个参数代表间隔
>>> numbers = list(range(3,20,2)) >>> print(numbers) [3, 5, 7, 9, 11, 13, 15, 17, 19]