控制流工具

……

if语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# if  elif  elif  else
>>> x = int(input("Please enter an integer: ")) # 要求输入一个值,代码会转换成int型
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
More

while语句

1
2
3
4
5
6
7
8
9
10
11
12
# while xx: ...
>>> a, b = 0, 1
>>> while b < 10:
... print(b)
... a, b = b, a+b # 赋值语句先计算右边
...
1
1
2
3
5
8

for语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# for xx in xxx: ...
>>> words = ['cat', 'window', 'defenestrate'] # 可以循环可迭代对象
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12

>>> for w in words[:]: # words[:]对一开始的words进行了复制,因为后面修改了words
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

range()函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
>>> for i in range(5):  # 0,1,2,3,4
... print(i)
...
0
1
2
3
4

range(5, 10)
5, 6, 7, 8, 9

range(0, 10, 3)
0, 3, 6, 9

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)): # 放在for循环中
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

>>> print(range(10)) # 是一个object对象,不是列表,节省空间
range(0, 10)

>>> list(range(5)) # 变成列表
[0, 1, 2, 3, 4]

break和continue函数及循环中的else

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# while和for中的else,是在列表中的项用完了(for中),或者while中条件不成立;
# 但当因为break循环结束时,不执行else。
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue # 结束此次循环,继续下次循环
... print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

pass语句

1
2
3
4
# pass 语句的功能,是什么都不做,占一个位置,方便日后添加代码使用
>>> def initlog(*args):
... pass # 占个位置,避免报错,内容可以以后进行修改。
...

函数定义

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> def fib(n):    # 求斐波那契数列
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

>>> fib(0) # 当函数里面没有return时,也是有返回值的,称为None,可用print显示
>>> print(fib(0))
None

关于更多的函数定义

默认参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 给定了默认值
i = 5
def f(arg=i):
print(arg)
i = 6
f() # 结果是5,因为在函数定义时,arg参数已经被赋值默认值

def f(a, L=[]): # 默认值只会被赋值一次,所以参数被连续使用
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3)) # 结果为[1] [1,2] [1,2,3]

def f(a, L=None): # 这样感觉每次都会被赋成None
if L is None:
L = []
L.append(a)
return L # 结果为[1] [2] [3] 可以这样进行修改

可变参数(*)

1
2
3
4
5
6
7
8
# 这个参数将接受剩余未匹配的零个或多个参数,将他们组合打包成元组
>>> def text_3(a,*args):
... print(a)
... print(type(args),args)
...
>>> text_3(1,23,2,2)
1
<class 'tuple'> (23, 2, 2)

关键字参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 和可变参数一样,接受剩余未匹配的零个或多个参数,将他们打包成字典;
# 要求调用函数的时候,应该用key = value的形式进行传递值。
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
# 输出
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

解压参数列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> list(range(3, 6))
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # 通过* 将列表或元祖中的参数解压,一个个提出来
[3, 4, 5]

# 同样,用** 解压字典变量
>>> def parrot(voltage, state='a stiff', action='voom'):
... print("-- This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
... print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

lambda表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# lambda a, b: a+b 也是一种函数,简单的写法
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

>>> a = lambda x : x ** 2
>>> a(5)
25

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1]) # sort括号内是用lambda自定义的比较函数,比较对象为pair[1]
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]