Python Beginner Tips: Functions

Keywords: Python


C language and python are often confused, especially I can't help adding a semicolon after Python... Just make a note for myself to save forgetting... (learned on muke.com)

13, Functions

1. Introduction

Using functions to encapsulate repeated logic codes, we abstract the process of encapsulating repeated logic codes. Abstraction is a very common concept in mathematics. In this document, there are Most functions built into Python.
The number and type of parameters passed must be consistent with the requirements of the function, otherwise errors will be caused.

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

L = []
x = 1
while x <= 100:
    L.append(x * x)
    x = x + 1

print(sum(L))

>>> 338350

2. Define function

2.1 def()

To define a function, use the def statement to write out the function name, parentheses (), parameters in parentheses and colons: in turn. Then, write the function body in the indented block, and the return value of the function is returned with the return statement.

#Define a function to find the absolute value
def my_abs(x):
	if x >= 0:
		return x
	else:
		return -x

my_abs(-3)
>>> 3

2.2 return()

2.2.1 return a value

Return means return. When the statement inside the function body is executed, once it is executed to return, the function will be completed and the result will be returned.

#Defines a function that sums all elements of a list
def list_sum(L):
    result = 0
    for num in L:
        result = result + num
    return result

2.2.2 return to None

If the result is printed in the function, the result will not be returned through return:

#Defines a function that sums all elements of a list
def list_sum(L):
    result = 0
    for num in L:
        result = result + num
    print('result is {}'.format(result))
    return

L = [1, 3, 5, 7, 9, 11]
result =list_sum(L) #Call the defined sum_list function and get the result returned by return
print(result)

>>> result is 36
	   None

In print(result), we get the result of None, which is reasonable, because inside the function, we print the result, but do not return the result.

2.2.2 return multiple values

Function can also return multiple values. Multiple values can be separated by commas, but pay attention to the order.

def data_of_square(side):
    C = 4 * side
    S = side * side
    return C, S

C, S = data_of_square(16)
print('Perimeter = {}'.format(C)) # ==>Perimeter = 64
print('the measure of area = {}'.format(S)) # ==>Area = 256

#You can also use a value to store the multivalued results returned by the function:
result = data_of_square(16)
print(result) # ==> (64, 256)

#The printed result is actually tuple type. If we need to take out the perimeter or area in the result, we can use the subscript of the corresponding position:
print(result[0]) # ==> 64
print(result[1]) # ==> 256

3. Recursive function

Inside the function, other functions can also be called. By reasonably splitting the logic, the complexity of the program can be reduced. If you call itself inside a function, the function is a recursive function.

Calculate factorial n= 1 * 2 * 3 * … * n

'''It can be seen that: fact(n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = fact(n-1) * n
 So, fact(n)Can be expressed as n * fact(n-1),only n=1 Special treatment is required.'''
def fact(n):
    if n == 1:
        return 1
    return n * fact(n - 1)

print(fact(1)) # ==> 1
print(fact(5)) # ==> 120

We can disassemble the detailed logic of fact(5) calculation:

===> fact(5)
===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120

The advantages of recursive function are 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, you should pay attention to preventing stack overflow:

>>> print(fact(10000))

Traceback (most recent call last):
  File "index.py", line 8, in 
    print(fact(10000))
  File "index.py", line 6, in fact
    return n * fact(n-1)
  File "index.py", line 6, in fact
    return n * fact(n-1)
  File "index.py", line 6, in fact
    return n * fact(n-1)
  File "index.py", line 6, in fact
    return n * fact(n-1)
  File "index.py", line 6, in fact
    return n * fact(n-1)
    ......

4. Function parameters

Function parameters can be any data type, as long as the internal logic of the function can be processed.
The isinstance() function can judge the parameter type. It receives two parameters, the first is the parameter to be judged, and the second is the type.

>>> isinstance('abcd', str)
True
>>> isinstance(100.0, int)
False
>>> isinstance((1,2), tuple)
True
>>> isinstance({'A':1, 'B':2}, dict)
True
>>> isinstance([1,2], str)
False
>>> isinstance([1,2], list)
True

The isinstance() function can be used to optimize functions, such as:

def my_abs(x):
    if not isinstance(x, int) or not isinstance(x, float):
        print('param type error.')
        return None
    if x >= 0:
        return x
    else:
        return -x

5. The function uses default parameters

The default parameter means that when this parameter is not passed, the parameter will use the default value at the time of definition.
For example, Python's built-in int() function actually has two parameters. We can pass both one and two parameters:

#int(value, [base=10]), base represents the base of value, and int() returns decimal
>>> int('12')  #Default base=10
12
>>> int('12', 8)  #12 is octal, and the returned decimal is 10
10
>>> int('12', 16)
18

The function's default parameters are used to simplify the call. We only need to pass in the necessary parameters. However, when necessary, you can pass in additional parameters to override the default parameter values:

#Define a function that calculates x to the nth power:
def power(x, n):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x  # When n=1,2, the while condition is satisfied, so s is multiplied by x twice
    return s
        
print(power(5, 2))  # ==> 25

Assuming that the number of square calculations is the most, we can set the default value of n to 2:

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

power(5) # ==> 25

Since the parameters of the function match from left to right, the default parameters can only be defined after the required parameters, otherwise errors will occur, such as def power(n=2, x)

6. The function uses variable parameters

Python functions also receive a parameter called variable parameter, which means any parameter. Variable parameters are usually represented by * args:

def func(*args):
    print('args length = {}, args = {}'.format(len(args), args))

func('a')
func('a', 'b')
func('a', 'b', 'c')

#result:
args length = 1, args = ('a',)
args length = 2, args = ('a', 'b')
args length = 3, args = ('a', 'b', 'c')

Python defines a variable parameter as a tuple, so you can use the variable parameter as a tuple inside the function.
The purpose of defining variable parameters is also to simplify the call. Suppose we want to calculate the average value of any number, we can define a variable parameter:

def average(*args):
    sum = 0
    for item in args:
        sum += item
    return sum / len(args)

print(average(1,2,3,4))  # ⇒ 2.5

7. The function uses variable keyword parameters

Python parameters are regarded as tuples and can only be found through the index. If the order changes, the subscript will become invalid and the function logic will have to be modified and implemented again.
Similar to dictionaries, Python functions provide variable keyword parameters. You can find the corresponding parameter value through the keyword name key.

def info(**kwargs):
    print('name: {}, gender: {}, age: {}'.format(kwargs.get('name'), kwargs.get('gender'), kwargs.get('age')))

info(name = 'Alice', gender = 'girl', age = 16)
#The result is: name: Alice, gender: girl, age: 16

For a function with required parameters, default parameters, variable parameters and variable keyword parameters, the definition order is as follows:

def func(param1, param2, param3 = None, *args, **kwargs):
    print(param1)
    print(param2)
    print(param3)
    print(args)
    print(kwargs)

func(100, 200, 300, 400, 500, name = 'Alice', score = 100)
# ==> 100
# ==> 200
# ==> 300
# ==> (400, 500)
# ==> {'name': 'Alice', 'score': 100}

Write a function that accepts three list s of keyword parameters names, gender and age, including the name, gender and age of students respectively. Please print out the name, gender and age of each student respectively.

def info(**kwargs):
    names = kwargs['names']
    gender_list = kwargs['gender']
    age_list = kwargs['age']
    index = 0
    for name in names:
        gender = gender_list[index]
        age = age_list[index]
        print('name: {}, gender: {}, age: {}'.format(name, gender, age))
        index += 1

info(names = ['Alice', 'Bob', 'Candy'], gender = ['girl', 'boy', 'girl'], age = [16, 17, 15])

#The result is:
name: Alice, gender: girl, age: 16
name: Bob, gender: boy, age: 17
name: Candy, gender: girl, age: 15

Posted by cLFlaVA on Tue, 26 Oct 2021 02:57:01 -0700