Getting Started with Python Basic Three-Function

What is a function

Definition: A function is a set of statements encapsulated by a name (function name). To execute the function, simply call the function name.
Features: 1, reduce duplicate code 2, make the program extensible 3, make the program easy to maintain

Call function

To call a function, you need to know the name and parameters of the function.
Absolute value function

>>> abs(100)
100
>>> abs(-20)
20
>>> abs(12.34)
12.34

A typeError is not reported if the number and type of arguments passed in are not correct when calling a function

>>> abs(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (2 given)
>>> abs('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'

A function name is actually a reference to a function object. You can assign a function name to a variable, which is equivalent to giving the function an alias.

>>> a = abs # Variable a points to abs function
>>> a(-1) # So you can also call the abs function from a
1

Define Functions

In Python, define a function to use the def statement, write out the function name, parentheses, parameters in parentheses and colons of the function, then write the function body in the indent block, and return the value with the return statement.

def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x

When the statement inside the function body is executed, once the return is executed, the function is executed and the result is returned.If there is no return statement, the function will return the result after execution, but the result is None, which can be abbreviated as return.

Parameters of the function

When defining a function, the name and location of the parameters are determined, and the interface definition of the function is completed. For the function caller, it is enough to know how to pass the correct parameters and what values the function will return. The complex logic inside the function is encapsulated and the caller does not need to know.
Python's function definition is very simple but flexible, and in addition to the normally defined required parameters, it is also variable, default, and keyword parameters.

Location parameters

Calculate the square of a number

def power(x):
    return x * x
>>> power(5)
25
>>> power(15)
225

Calculate the n-th power of a number

def power(x, n):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s
>>> power(5, 2)
25
>>> power(5, 3)
125

The two values passed in are assigned to x and n sequentially

Default parameters
def power(x, n=2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s
>>> power(5)
25
>>> power(5, 2)
25

When a function is called, if n is passed in, the n-th power of x is calculated. If not, n=2, the square of x is calculated.
Note when setting default parameters:
Required parameter first, default parameter later, otherwise interpreter error
When there are multiple parameters, the parameters with large changes are placed in front and those with small changes are placed behind.Small changes can be used as default parameters
When there are multiple default parameters, they can be invoked either sequentially or out of order, but the parameter name must be written.

def enroll(name, gender, age=6, city='Beijing'):
    print('name:', name)
    print('gender:', gender)
    print('age:', age)
    print('city:', city)
>>>enroll('Adam', 'M', city='Tianjin')

Points easily encountered by default parameters:

def add_end(L=[]):
    L.append('END')
    return L
#Normal calls will not cause problems
>>> add_end([1, 2, 3])
[1, 2, 3, 'END']
>>> add_end(['x', 'y', 'z'])
['x', 'y', 'z', 'END']
#If called continuously, errors will occur with default parameter results
>>> add_end()
['END']
>>> add_end()
['END', 'END']
>>> add_end()
['END', 'END', 'END']

Every call, the default parameter is an empty list. Why does the function seem to remember the last'end'added?
The reason is that when a Python function is defined, the value of the default parameter L is calculated, that is, [], because the default parameter L is also a variable that points to an object []. If the content of L is changed, the content of the default parameter will change the next time it is called, and it will no longer be at the time of the function definition.So, one thing to keep in mind when defining default parameters is that the default parameters must point to the same object!
Modifying the example above can be done with None

def add_end(L=None):
    if L is None:
        L = []
    L.append('END')
    return L
>>> add_end()
['END']
>>> add_end()
['END']

Variable parameters

As the name implies, a variable parameter means that the number of parameters passed in is variable and can be one, two,.Even zero.
An example is calculating the sum of the squares of a set of numbers:

def calc(numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
#Invoke requires a list or tuple to be passed in
>>> calc([1, 2, 3])
14
>>> calc((1, 3, 5, 7))
84

With variable parameters, functions and calls look like this:

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
>>> calc(1, 2)
5
>>> calc()
0

You can see that just by adding a * before the parameter when defining the function, the parameter is not passed in as a list or tuple when called.
If you already have an array, you can do this if you want to call a variable parameter:

>>> nums = [1, 2, 3]
>>> calc(*nums)
14
Keyword parameters

Variable parameters allow you to pass in zero or any number of parameters that are automatically assembled into a tuple when a function is called.Keyword parameters allow you to pass in zero or any parameters with parameter names, which are automatically assembled into a dict within the function.

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)
#The function person accepts the keyword parameter kw in addition to the required parameters name and age.When the function is called, only the required parameters can be passed in:
>>> person('Michael', 30)
name: Michael age: 30 other: {}
#You can also pass in any number of keyword parameters:
>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}

Keyword parameters can extend the functionality of a function, for example, when implementing a registration function, they are optional except for the username and password required.Defining this function with keyword parameters is sufficient.
As with variable parameters, if you already have a dict, convert it into a keyword parameter and put it in:

>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

**extra means that all key-value s of the extra dict are passed into the function **kw parameter with keyword arguments, and kW will get a dict.
Note: dict obtained by kw is a copy of extra, and changes to kw will not affect extras outside the function.

Named keyword parameters

For keyword parameters, the caller of the function can pass in any unrestricted keyword parameter, but if you want to restrict the name of a keyword parameter, you can use a keyword parameter, such as accepting only city and job as keyword parameters:

def person(name, age, *, city, job):
    print(name, age, city, job)

Unlike the keyword parameter **kw, the named keyword parameter requires a special delimiter *,* and the parameters behind * are treated as named keyword parameters.
Call:

>>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer

Named keyword parameters must pass in parameter names, unlike location parameters, which can cause errors if they are not passed in:

>>> person('Jack', 24, 'Beijing', 'Engineer')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: person() takes 2 positional arguments but 4 were given

Because the parameter names city and job are missing from the call, the Python interpreter treats all four parameters as positional parameters, but the function accepts only two positional parameters.
Named keywords can have default values:

def person(name, age, *, city='Beijing', job):
    print(name, age, city, job)
>>> person('Jack', 24, job='Engineer')
Jack 24 Beijing Engineer

If you already have a variable parameter in the function definition, the named keyword parameter that follows does not require a special delimiter *

def person(name, age, *args, city, job):
    print(name, age, args, city, job)

If there are no mutable parameters, be sure to delimit them, otherwise the interpreter cannot distinguish the positional and keyword parameters.

Parameter combination

Functions are defined in Python with required parameters, default parameters, variable parameters, keyword parameters, and named keyword parameters.These 5 parameters can be combined.
However, the order of parameter combinations must be: required parameters - default parameters - variable parameters - named keyword parameters - keyword parameters!
For example:

def f1(a, b, c=0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)

def f2(a, b, c=0, *, d, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

When invoked, the Python interpreter automatically passes in the corresponding parameters according to their position and name

>>> f1(1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> f1(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {}
>>> f1(1, 2, 3, 'a', 'b')
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}
>>> f1(1, 2, 3, 'a', 'b', x=99)
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}
>>> f2(1, 2, d=99, ext=None)
a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}

It can also be called through a tuple and list:

>>> args = (1, 2, 3, 4)
>>> kw = {'d': 99, 'x': '#'}
>>> f1(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'}
>>> args = (1, 2, 3)
>>> kw = {'d': 88, 'x': '#'}
>>> f2(*args, **kw)
a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}

So, for any function, you can call it like a func(*args,**kw) regardless of how the parameters are defined!
Note: Using *args and **kw is a Python idiom, and of course other parameter names can be used, but it is best to use the idiom.

Recursive function

Inside a function, you can call other functions.If a function calls its own function, it is a recursive function.
Calculate the factorial recursive function:

def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)
>>> fact(1)
1
>>> fact(5)
120

Recursive functions have the advantage of simple definition and clear logic.Theoretically, all recursive functions can be written as loops, but the logic of loops is not as clear as recursion.
When using recursive functions, care should be taken to prevent stack overflow.In computers, function calls are made through stacks, a data structure.Each time a function call enters, the stack adds a layer of stack frames, and each time the function returns, the stack subtracts one layer of stack frames.Since the stack size is not infinite, increasing the number of recursive calls can cause the stack to overflow.
The solution to recursive call stack overflow is through tail recursive optimization.Tail recursion refers to calling itself when a function returns, and the return statement cannot contain an expression.This allows the interpreter or compiler to optimize tail recursion so that the recursion itself takes up only one stack frame, no matter how many calls it makes, without a stack overflow.

def fact(n):
    return fact_iter(n, 1)

def fact_iter(num, product):
    if num == 1:
        return product
    return fact_iter(num - 1, num * product)

But!!Most programming languages are not optimized for tail recursion and the Python interpreter is not optimized, so even changing the fact(n) function above to tail recursion can cause stack overflow.

Keywords: Python Programming

Added by davissj on Wed, 29 May 2019 11:34:08 +0300