跳到主要内容

更多控制流工具

if 语句

x = int(input("Please enter an integer: "))

if x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')

for 语句

words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))

range 函数

list(range(5)) # => [0, 1, 2, 3, 4]
list(range(5, 10)) # => [5, 6, 7, 8, 9]
list(range(0, 10, 3)) # => [0, 3, 6, 9]
sum(range(4)) # => 0 + 1 + 2 + 3 = 6

循环中的 break/continue/else

TODO

pass 语句

TODO

match 语句

TODO

函数

使用 def 关键字来定义函数:

def add(a, b):
return a + b

函数也是一个对象,可以赋值给变量:

add2 = add
add2(1, 2) # => 3

当函数的 return 没有参数时,会返回 None

默认值参数

在函数中可以给形参设默认值,调用函数时可以不传入该参数:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
# ...

注意,默认值的计算只会在函数定义时进行一次:

def append(item, list=[]):
list.append(item)
return list

append(1) # => [1]
append(2) # => [1, 2]
append(3) # => [1, 2, 3]

关键字参数

key=value 也可用于调用函数:

ask_ok(prompt='OK?')
ask_ok('OK?', reminder='Only yes or no!')
# 关键字参数必须在位置参数之后,关键字之间的顺序不重要。
ask_ok('OK?', reminder='Only yes or no!', retries=2)

*name 用于接收任意数量的位置参数,**name 用于接收任意数量的关键字参数:

def concat(*args, sep='/'):
return sep.join(args)

concat('a', 'b', 'c', sep='.') # => 'a.b.c'
def print_dict(**dict):
for k, v in dict.items():
print(f'{k}: {v}')

print_dict(a=1, b=2, c=3) # => a: 1\nb: 2\nc: 3

特殊参数

可以通过特殊标记划分参数传入方式:

def concat(a, b, /, c, d, *, e, f):
return a + b + c + d + e + f

concat(1, 2, 3, 4, e=5, f=6) # => 21

其中,/ 之前的参数只能通过位置参数传入,* 之后的参数只能通过关键字参数传入,中间的参数可以通过两种方式传入。

文档字符串

可以在函数内第一行用字符串给函数添加文档注释:

def add(a, b):
"""这是一个加法函数。"""
return a + b

函数注解

可以在函数定义时给参数添加注解:

def add(a: int, b: int) -> int:
return a + b

可以通过函数的 __annotations__ 属性获取注解:

add.__annotations__ # => {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

参考

更多控制流工具 - python.org