Python模块¶
导入模块 Import Module¶
import random
from math import pi
from math import sqrt as rt
函数Function¶
def fun(arg1, arg2):
# 函数体
参数类型限定
def fun(arg: int) -> None: # 函数返回类型
# 函数体
默认参数
def fun(arg="default"):
# 函数体
可变数量的参数
def function(named_arg, *args):
print(named_arg)
print(args) # args是一个tuple
关键字参数Key word arguments(未提前定义的具名参数)
def my_func(x, y=7, *args, **kwargs):
print(kwargs) # kwargs是一个字典
my_func(2, 3, 4, 5, 6, a=7, b=8)
"""
{'a': 7, 'b': 8}
"""
Generator生成器¶
属于iterable,但不能随机存取。
使用yield关键字从生成器函数中返回值。
def countdown():
i = 5;
while i > 0:
yield i
i -= 1
for v in countdo