Get into the habit of writing together! This is the sixth day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .
First, the definition of the function
The function is:
- Encapsulate the steps of one thing together and get the final result
- The function name represents what the function does
- The function body is the process of implementing the function
- method or function
- can be reused
Functions are divided into built-in functions and custom functions. The methods that can be called for each data type mentioned above are built-in functions. When the built-in functions cannot meet our needs, we need to implement custom functions.
Functions are defined by the keyword def in Python
def func_name(args..)
todo
返回值
复制代码
Execute a function or call a function in the form of a function name ()
The return of the function result:
- return is the keyword that the function result returns
- return can only be used within the body of a function
- return supports returning all Python data types
- A function with a return value can assign the return value directly to a variable
Customize a capitalize function
def capitalize(data):
index = 0
# 保存新字符串
temp = ''
for item in data:
# 第一次循环获取到第一个字符
if index == 0:
temp = item.upper()
else:
temp += item
index += 1
return temp
res = capitalize('hello')
print(res)
复制代码
res = capitalize(123)
print(res)
复制代码
define a function with no return value
def message(mes, mes_type):
new_mes = '[%s]%s' % (mes_type, mes)
print(new_mes)
message('I am IronMan', 'info')
复制代码
The result returned by the function is None
res = message('Tomorrow is Friday', 'info')
print('res:%s' % res)
复制代码
The difference between return and print:
- print just simply prints the object, does not support assignment statements
- return is the return of the function execution result, and also supports assignment statements
The parameters of the function
The parameters of the function must pass parameters, default parameters and indeterminate parameters
Required parameters and default parameters
The parameters defined in the function do not have default values, and an error will be reported if they are not passed when calling the function.
The required parameters have the following characteristics
- There is no default value in the function, and an error will be reported if it is not passed
- When defining a function, the parameter is assigned without an equals sign
- When defining a function, there is no default value and the parameters that must be passed in when the function is executed, and the order is the same as the parameter order, that is, the parameters must be passed
When defining a function, the defined parameter contains a default value, and a default value is given to the parameter through an assignment statement. If the default parameter is given a new value when the function is called, the function will use the value passed in first.
def add(a, b, c=3):
return a + b + c
result = add(1, 2)
print(result)
result = add(1, 2, 6)
print(result)
result = add()
print(result)
复制代码
Uncertain parameters
Indeterminate parameters are also variadic parameters:
- There is no fixed parameter name and number, the parameter name to be passed is uncertain, and the number of parameters to be passed is uncertain
- *args represents combining an indeterminate number of arguments into a tuple
- **kwargs means to combine statements with parameters and default values into a dictionary
def alpha(*args, **kwargs):
print(args, type(args))
print(kwargs, type(kwargs))
alpha(1, 2, 3, name='stark', address='NY')
复制代码
def bravo(*args, **kwargs):
if len(args) > 0:
for i in args:
print(i)
if 'name' in kwargs:
print(kwargs['name'])
bravo('stark', 'peter', 'banner', 'clint', name='小明', address='上海')
复制代码
Pass tuple and dictionary type parameters
tuple_01 = (1,3,5,8,0,11)
dict_01 = {'name': 'stark', 'address':'NY'}
bravo(tuple_01, dict_01)
bravo(*tuple_01, **dict_01)
复制代码
parameter rules
def alpha(x, y = 1):
print(x + y)
# 使用位置传参
alpha(1, 2)
# 位置传参,只传必填参数
alpha(1)
# 使用关键字传参
alpha(x = 1, y = 2)
# 关键字传参,只传必填参数
alpha(x = 1)
# 关键字传参,不必遵循参数先后顺序
alpha(y = 1, x = 2)
复制代码
Required parameters must be passed, otherwise an error will be reported
def bravo(x, y=1, *args):
print('x={}, y={}, args={}'.format(x, y, args))
tuple_01 = (1, 2)
bravo(1, 2, *tuple_01)
# 这种传参方式会报错
bravo(x=1, y=2, *tuple_01)
复制代码
When mandatory parameters are mixed with default parameters and tuple type parameters, it is recommended to use positional parameters
def charlie(x, y=1, **kwargs):
print('x={}, y={}, kwargs={}'.format(x, y, kwargs))
dict_01 = {'name': 'stark', 'address': 'NY'}
charlie(1, 2, **dict_01)
# 这种传参方式会报错, 位置传参字典必须放到最后
# charlie(**dict_01, 1, 2)
charlie(x=1, y=2, name='stark', address='NY')
charlie(name='stark', address='NY', x=1, y=2)
复制代码
def delta(x, y=1, **kwargs):
print('x={}, y={}, kwargs={}'.format(x, y, **kwargs))
dict_01 = {'name': 'stark', 'address': 'NY'}
delta(1, 2, **dict_01)
复制代码
The function body cannot add * or **
Types of function parameters
The types of function parameters can be defined as follows
- Define the parameter type by parameter name: parameter data type
- Only available after Python 3.7
- The parameter type is not checked
def foxtrot(x:str, y:int=1):
print('x={}, y={}'.format(x, y))
foxtrot('stark')
foxtrot('stark', 2)
foxtrot(1, 'stark')
复制代码
def golf(x:str, y:int=1, *args:int, **kwargs:str):
print('x={}, y={}, args={}, kwargs={}'.format(x, y, args, kwargs))
golf('stark', 2, 1, 2, name='stark')
golf(1, 3, 2, 3, id=1)
复制代码
Third, global variables and local variables
Global variables are variables defined in the top-level code block of a Python script. Global variables can be read in the function body, but cannot be modified in the function body.
name = 'stark'
def hotel():
print('函数体内打印出name的值为:', name)
hotel()
print('函数体外打印出name的值为:', name)
复制代码
The variables defined in the function body are called local variables. Local variables can only be used in the currently defined function body, but cannot be used outside the function body.
def iris():
address = 'New York'
print('函数体内使用局部变量:',address)
iris()
print('函数体外使用局部变量:', address)
复制代码
Use the global keyword to modify global variables within the function body
name = 'stark'
print('函数体外打印出修改前name的值为:', name)
def hotel():
global name
name = 'tony stark'
print('函数体内修改name的值为:', name)
hotel()
print('函数体外再次打印出name的值为:', name)
复制代码
glob only supports numeric strings, null types, and boolean types. The global keyword is not required to modify the dictionary list in the function body class. It is not recommended to use the global keyword in the function body to modify global variables.
4. Recursive function
A function that executes itself repeatedly can be called a recursive function
count = 0
def juliet():
global count
count += 1
if count != 5:
print('count!=5时重复执行自己,当前count为:', count)
return juliet()
else:
print('count:',count)
juliet()
复制代码
Recursive function will cause memory overflow if there is no condition to exit recursion
5. Anonymous functions
lambda can define a lightweight function, which can be deleted immediately after use
How to define an anonymous function without parameters
f = lambda: value
f()
复制代码
How to define anonymous function with parameters
f = lambda x, y: x + y
f(1, 2)
复制代码
kilo = lambda: 1
res = kilo()
print(res)
复制代码
The content after the lambda colon is the returned content. The return keyword is omitted by default. If the return keyword is added, an error will be reported.
lima = lambda : print('I am IronMan')
lima()
复制代码
mike = lambda x, y: x * y
print(mike(9, 8))
复制代码