6. Functions in Python (1)

1. Function declaration and call

  • function declaration
  • function call

(1), the declaration of the function

The general form of a function declaration:

def <函数名> (参数列表):
    <函数语句>
    return <返回值>     #不写返回值则默认返回None

Example function declaration:

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

(2), function call

Call it directly in the form of the function name (parameter), if there is no parameter, the function name + brackets

Example of calling the function:

# 计算两个数的和
def calcSum(a, b):
    return a + b

def mPrint():
    print('This is my Print Function!')

m = calcSum(10, 20) # 调用calcSum() 函数
print(m)
mPrint()            # 调用mPrint()函数

Running result:
30
This is my Print Function!

2, the parameters of the function

  • default value parameter of function
  • Parameter passing of functions (positional passing and keyword passing)
  • Variable number of arguments passed
  • Function call to disassemble the sequence
  • How to pass parameters when calling a function

(1), the default value parameter

A function with parameters with default values ​​has the following form:

def <函数名>(参数=默认值):
    <语句>
  • When declaring, you must first declare parameters without default values, and then declare parameters with default values.

Example of default value parameter function:

def clacFunction(a, b, c=10):
    return a + b * c

print(clacFunction(1, 2, 5))
print(clacFunction(1, 2))

Running result:
11
21

(2), the parameter transfer of the function

  • position transfer
  • keyword passing
  • Positional passing : Parameters are passed to the function according to the position of the declaration;
  • Keyword passing : Pass parameters to functions according to keywords;
  • When calling a function to provide parameters, the parameters passed in order should be placed before the keyword parameters, and there should be no duplicates, responsible for reporting errors;
def function(hi='Hi', lan='python', sy='!'):
    print(hi, lan, sy)

function('Hello', 'Python')
#function('HHi', lan='C++', '!!!')   #函数报错,第三个参数传递给lan有重复
function('HHi', lan='C++', sy='!!!')

Running result:
Hello Python !
HHi C++ !!!

(3), variable parameter passing

When defining a function, if the parameter name is preceded by an asterisk "*", it means that the parameter is a variable parameter; when calling, if all other variables are assigned in sequence, the remaining parameters will be collected in In a tuple, the name of the tuple is the parameter name preceded by an asterisk.

Example of variable parameter passing:

def function(*tup):
    for i in tup:
        print(i, end=' ')

function(10, 20, 5, 3, 'Hello', 'Douzhq')

Running result:
10 20 5 3 Hello Douzhq

The parameter marked with * should be placed at the end . If the parameter with an asterisk is placed at the front, it can still work normally, but the parameters after the call must be provided in the form of keyword parameters, otherwise the following positions cannot be obtained. value and an error occurred

Examples of variadic and other parameters:

def function(*tup, num1, num2):
    for i in tup:
        print(i, end=' ')
    return num1 * num2

#function(10, 20, 5, 3, 'Hello', 'Douzhq', 10, 20) #运行出错,num1和num2未传值
function(10, 20, 5, 3, 'Hello', 'Douzhq', num1 = 10, num2 = 20)

Running result:
10 20 5 3 Hello Douzhq

You can also pass parameters in the form of a dictionary. Add two asterisks (**) before the parameter to collect the parameters in the form of a dictionary.

Dictionary passing example:

def function(b='a', **dct):
    print(dct)
    print(b)

function(10, a='b', c='d')

Running result:
{'a': 'b', 'c': 'd'}
10

(4), the function call to disassemble the sequence

  • Disassemble tuples: provide positional arguments (*)
  • Teardown dictionary: provide positional arguments (**)

Example of dismantling a sequence function:

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

print(function(*(10, 20)))
print(function(**{'a': 10, 'b': 20}))

Running result:
30
30

(5), the transfer method of parameters when the function is called

When a function is called, if the provided parameter is an immutable parameter, then when it is modified inside the function, its value outside the function does not change; if a variable parameter is provided, when it is changed inside the function, its value outside the function also changes. will change.

Example of function modification variable parameter:

def function(f):
    f.append(10)

lst = [12, 22, 32]
print('调用前:', lst)
function(lst)
print('调用后:', lst)

Running result:
Before calling: [12, 22, 32]
After calling: [12, 22, 32, 10]

The memory for the default value of the function is fixed and allocated when the function is called for the first time

Example of a trap for a Python function:

def function(lst = []):
    lst.append(10)
    print(lst)

function()
function()
function([1, 2, 3, 4])
function()
function()

Because the default parameter is a variable parameter, it is modified every time the default parameter is called.
Running result:
[10]
[10, 10]
[1, 2, 3, 4, 10]
[10, 10, 10]
[10, 10, 10, 10]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325643331&siteId=291194637