Function definition
Function is the code for some specific functions, the definition of a function name, the name of the function can be called by this function multiple times
The method defined functions and the characteristics
- Function name : the general said as long as the legal identifier on the line, but in order to read through of the code, agreed to all lowercase letters with between multiple letters underscore
- Parameter list : function is used to define the parameters received, separated by commas plurality of parameters, defines the parameters in the function must pass argument when calling the
- Function key
def
- Function can be defined zero or more parameters
- Use return function ends. The default return None.
Functions help documentation
Defined Functions Help documentation: After only need to put a string function declaration, before the function body, with three quotes
Check function help documentation, help (function name) or Print (_ doc_ )
Way function call:
- Function name () Python built-in functions such as print ()
- When the function call function defined in the manner required, transmission parameters, with multiple parameters
,
separated by commas
Function return value
- The default return value of a function of multiple tuples, but also multi-function return values may be transmitted to the plurality of variable sequence through inverse Solutions
- Function returns the return statement is used to indicate the end of this function is executed, and returns the object behind return
- Sometimes, the function does not need to return any value, then you can return statement is not required, it defaults to give you a return None in the background and does not give any hints.
- Once encountered during the execution of the function return statement, then all of the code after the function body will be ignored, directly out of the body of the function, prompt you for a loop inside the code
Examples of function definition
Examples of multi-function return values:
def my_sum_agv(list):
count = 0
sum = 0
for e in list:
if isinstance(e, int) or isinstance(e, float):
count += 1
sum += e
return sum, sum/count
my_list = [1, 10, 1.1 , 2]
results = my_sum_agv(my_list) #调用函数并且传递一个类型为list的参数
print(type(results)) # 打印默认的多值返回类型
print(results)
## 通过序列反解,将值传递给多个变量
sum ,avg = my_sum_agv(my_list)
print("列表中的和为 %s,平均值为 %s" %( sum , avg ))
operation result
<class 'tuple'>
(14.1, 3.525)
列表中的和为 14.1,平均值为 3.525
The return statement example
def my_sum_agv(list):
count = 0
sum = 0
for e in list:
if isinstance(e, int) or isinstance(e, float):
count += 1
sum += e
return sum, sum/count
print("我爱中国") #return语句后的代码不会执行
my_list = [1, 10, 1.1 , 2]
results = my_sum_agv(my_list) #调用函数并且传递一个类型为list的参数
print(type(results)) # 打印默认的多值返回类型
print(results)
····
<class 'tuple'>
(14.1, 3.525)
····
Summary: an initial understanding of the function here later chapters continue to recognize function