Python (8) Function
Published: 2019-05-15

abs()

#可以
s=-20
print(s)
print(abs(s))

>>> 20
#不可以
s=-20
print(s)
abs(s)
print(s)

cmp(x,y)

comparison function cmp(x, y) requires two parameters,
If x is less than y, then -1 is returned.
If x==y, the return value is 0
If x>y, the return value is 1

int()

Python's built-in common functions also include data type conversion functions, such as the int () function, which can convert other data types to integers

s=int('123')
print(s+123)
>>> 246

str()

str () function converts other types to str

str1=str(123)
print(str1)

sum()

task
The sum () function takes a list as an argument and returns the sum of all elements of the list.Please calculate 1*1+2*2+3*3+…+100*100.

x=1
l=[]
while x<=100:
    l.append(x*x)
    x=x+1
print(sum(l))  

Write Functions

Define a function to use def statement, write out the function name, brackets, parameters in brackets and colon:, then write the function body in the indented block, and return the return value of the function with RETURN statement.
Let's take a custom my_abs function for absolute value as an example:

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

If there is no return statement, the function will return the result after execution, but the result is None.Return None can be abbreviated as return.

Please define a square_of_sum function that accepts a list and returns the sum of the squares of each element in the list.

def square_of_sum(L):
    L2=[]
    x=0
    lens=len(L)
    while x<lens:
        L2.insert(x,L[x]*L[x])
        x=x+1
    return L2      
print(square_of_sum([1, 2, 3, 4, 5]))
#以为是把元素变为自己的平方,仔细看题然后wrong,下面为正解
def square_of_sum(L):
    sum = 0
    for x in L:
        sum = sum + x * x
    return sum
print square_of_sum([1, 2, 3, 4, 5])
print square_of_sum([-5, 0, 5, 15, 25])

returns multiple values

math package provides sin () and cos () functions, which we first refer to with import

import math
def move(x, y, step, angle):
    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx, ny
x, y = move(100, 100, 60, math.pi / 6)
>>> print x, y
151.961524227 70.0

But this is only an illusion. Python functions still return a single value:

>>> r = move(100, 100, 60, math.pi / 6)
>>> print r

(151.96152422706632, 70.0)

Use print to print the returned result. The original return value is a tuple!
However, syntactically, returning a tuple can omit parentheses, while multiple variables can receive a tuple at the same time and assign it to the corresponding value by position. Therefore, Python's function returning multiple values actually returns a tuple, but it is more convenient to write.

task
Quadratic equation of one unknown is defined as ax²+bx+c = 0
Please write a function to return the two solutions of quadratic equation of one unknown.
Note: Python's math package provides the sqrt () function to calculate the square root.

#请参考求根公式:x = (-b±√(b²-4ac)) / 2a
#参考代码:
import math
def quadratic_equation(a, b, c):
    t = math.sqrt(b * b - 4 * a * c)
    return (-b + t) / (2 * a),( -b - t )/ (2 * a)
print quadratic_equation(2, 3, 0)
print quadratic_equation(1, -6, 5)

Recursive Function

Recursive function has the advantages of simple definition and clear logic.In theory, all recursive functions can be written as loops, but the logic of loops is not as clear as recursion.
Using recursive functions requires attention to prevent stack overflow.In computers, function calls are implemented through the data structure of stack. Every time a function call is entered, the stack adds a layer of stack frame, and every time the function returns, the stack subtracts a layer of stack frame.Since the stack size is not infinite, too many recursive calls will lead to stack overflow.You can try to calculate fact(10000).

task
The movement of Tower of Hanoi (http://baike.baidu.com/view/191666.htm) can also be regarded as a recursive function.
We numbered the columns A, B and C. Moving all disks from A to C can be described as follows:
If A has only one disk, it can move directly to C;If A has N disks, it can be seen that A has 1 disk (chassis)+(N-1) disks. First, you need to move (N-1) disks to B, then move the last disk of A to C, and then move the (N-1) disks of B to C.
Please write a function, given the input n, a, b, c, print out the moving steps:
move(n, a, b, c)
For example, enter move(2, ‘A', ‘B', ‘C',' b',' c') and print out:
A –> B
A –> C
B –> C

def move(n, a, b, c):
    if n ==1:
        print a, '-->', c
        return
    move(n-1, a, c, b)
    print a, '-->', c
    move(n-1, b, a, c)
move(4, 'A', 'B', 'C')def m

Define Default Parameters

123 to Octal number

int('123', 8)
83

Since the parameters of the function match from left to right, the default parameters can only be defined after the required parameters

# OK:
def fn1(a, b=1, c=2):
    pass
# Error:
def fn2(a=1, b):
    pass

task
Please define a greet () function that contains a default parameter. If it is not passed in, print' Hello, World.' If it is passed in, print' Hello, XXX.'
The default value of the default parameter can be set to 'world'

Reference Code:

def greet(name='world'):
    print 'Hello, ' + name + '.'
greet()
greet('Bart')

Define Variable Parameters

If we want a function to accept any number of parameters, we can define a variable parameter:

def fn(*args):
    print args

The name of the variable parameter is preceded by a * sign. We can pass 0, 1 or more parameters to the variable parameter. Python interpreter will assemble a group of passed parameters into a tuple and pass it to the variable parameter. Therefore, within the function, it is good to directly regard the variable args as a tuple.
Task
Write an average () function that accepts variable parameters.
Variable argument args is a tuple. when 0 arguments are passed in, args is an empty tuple.

Reference Code:

def average(*args):
    sum = 0.0
    if len(args) == 0:
        return sum
    for x in args:
        sum = sum + x
    return sum / len(args)
print average()
print average(1, 2)
print average(1, 2, 2, 3, 4)