function
1. Define
def function name (parameter):
function body
2. Multi-function execution flow
a = 100
def test01():
print(a)
def test02():
global a # global关键字代表全局变量
a = 10
print(a)
3. Return value
def func(a,b):
return a,b
print(func(24,23))
Note:
Multiple return value functions return tuples by default and return
can be connected to lists, tuples or dictionaries
4. Parameters
Keyword parameters:
If there are positional parameters, the positional parameters must be before the keyword parameters, but there is no order between the keyword parameters
def func(name,age,gender):
print(f'姓名:{name},年龄:{age},性别:{gender}')
func('Tom',gender='男',age=20)
Default parameters:
same as default parameters
def func(name,age,gender='男'):
print(f'姓名:{name},年龄:{age},性别:{gender}')
func('Tom',20,'女')
Variable length parameters:
used in scenarios
where you are not sure how many parameters will be passed when calling. Package location:
def func(*args):
print(args)
func('Tom',18)
Note: All the parameters passed in will be collected by the args variable, which will be combined into a tuple according to the position of the passed parameters. args is the tuple type, which is the package position transfer
Package keywords:
def func(**kwargs):
print(kwargs)
func(name='Tom',age=18,gender='man')
# {'name': 'Tom', 'age': 18, 'gender': 'man'}
To sum up: Whether it is package location or package keyword delivery, it is a process of grouping a package