[Chapter 9] Functions of python

Keywords: Python Lambda Asterisk

Introduction of Functions

Functions are organized, reusable code segments that implement a single, or related function.
Functions can improve the modularity of applications and the reuse of code. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.
Benefits of functions:
  • code reuse
  • Keep consistent and easy to maintain
  • Scalability

2. Definition and Call of Function

Definition of 2.1 Function

Definition rules of functions:
  • Function code blocks begin with def keywords, followed by function identifier names and parentheses ()
  • Any incoming parameters and independent variables must be placed between parentheses, which can be used to define parameters.
  • The first line statement of a function can optionally use a document string -- for storing function descriptions
  • Function content starts with a colon and is indented
  • return [expression] terminates the function, selectively returning a value to the caller. return without expression is equivalent to returning None
1. The grammar of defining functions:
2 
3 
4 def function name (parameter):
5 function body
6 Return Value
1 # Example
2 
3 def print_hello():
4     """
5     Printing hello
6     :return:
7     """
8     print("hello")

2.2 Function Call

When a function is defined, it is equivalent to having a code with certain functions, which needs to be called in order to be executed.

The call function is very simple, and the call can be completed by the function name ().

1 # Examples:
2 print_hello()  # Call function

Be careful:

  • Every time a function is called, it executes from scratch. When the code in the function is executed, it means the call is over.
  • Of course, if return is executed in a function, it will end the function.

3. Return Value of Function

To add a return value to a function, you need to use the return keyword

 1 def fun1():    # No return value
 2     print("aa")
 3 
 4 def fun2():
 5     msg = "hello world"
 6     return msg    # Return msg,A return value
 7 
 8 def fun3():
 9     return 1, 2, 3    # Returns multiple return values
10 
11 aa = fun1()    # Return value of receiving function
12 bb = fun2()
13 cc = fun3()
14 print(aa)
15 print(bb)
16 print(cc)
17 
18 # Output results:
19 # None
20 # hello world
21 # (1, 2, 3)

Summary:

  • If no return statement is returned in the function, the python function returns None by default.
  • Function return value is 0, function return None by default; function return value is 1, then return object; return value is greater than 1, then return a tuple

IV. PARAMETERS OF FUNCTIONS

Principles of functional parameters:
  • Parametric variables allocate memory units only when they are called. At the end of the call, the allocated memory units are released immediately. Therefore, the parameter is only valid inside the function. The parameter variable cannot be used again after the function call ends and returns to the main calling function.
  • Arguments can be constants, variables, expressions, functions, etc. No matter what type of arguments they are, they must have definite values when calling functions in order to transmit these values to the parameters. Therefore, the parameters should be determined by assignment and input in advance.
  • Position parameters and keywords (standard call: real participation parametric position one-to-one correspondence; keyword call: location need not be fixed)
  • Default parameters: at the end of the parameter list
  • Parametric group

4.1 General parameters

1 def fun1(name):   # name As a formal parameter
2     print(name)
3 
4 aa = "hello"
5 fun1(aa)  # aa For reference

4.2 Default parameters

 1 def func(name, age=18):
 2     print("%s:%s" % (name, age))
 3 
 4 
 5 # Specified parameters
 6 func('aa', 19)  # Customize incoming default parameters, whichever is incoming
 7 func('cc', age=20)
 8 func('bb')      # Default parameters are not passed, using default values
 9 
10 # Operation results:
11 # aa:19
12 # cc:20
13 # bb:18

4.3 Dynamic parameters

Location parameter > * dynamic parameter > default parameter

 1 def func1(*args):
 2     print(args)
 3     print(type(args))       # <class 'tuple'>  tuple
 4 
 5 
 6 # Mode 1 of Implementation
 7 func1(11, 33, 4, 4454, 5)
 8 
 9 # Mode 2 of implementation
10 li = [11, 2, 2, 3, 3, 4, 54]
11 func1(*li)
 1 def func2(**kwargs):
 2     print(kwargs)
 3     print(type(kwargs))     # <class 'dict'>
 4 
 5 
 6 # Mode 1 of Implementation
 7 func2(name='wupeiqi', age=18)
 8 
 9 # Mode 2 of implementation
10 dict1 = {'name': 'fyh', "age": 18, 'gender': 'male'}
11 func2(**dict1)

Be careful:

  • The variable args with an asterisk (*) holds all unnamed variable parameters, args being tuples
  • The variable kwargs with ** stores named parameters, such as key=value, and kwargs is a dictionary.
1 # Universal parameter  Arbitrary parameters are acceptable
2 def func(*args, **kwargs):
3     pass

5. Nesting of Functions

 1 def func1():
 2     print("hello world")
 3 
 4 
 5 def func2():
 6     print("aa")
 7     func1()         
 8     print("cc")
 9 
10 
11 func2()  # Execute first in sequence print("aa") --> func1() --> print("cc")

Global and Local Variables

6.1 Namespaces and scopes

Namespaces:
    1. Built-in namespaces: python interprets variable functions at internal runtime
    2. Global Namespace: Variables and Functions that we declare directly in the py file
    3. Local namespaces: variables and functions declared within functions

Loading order:
    1. Built-in namespaces
    2. Global namespace
    3. Local namespaces

Value order:
    1. Local namespaces
    2. All namespaces
    3. Built-in namespaces


Scope:
    1. Global scope: global namespace + built-in namespace
    2. Local scope: local namespace
    You can view the content in the global scope through the globals() function, or locals() can view the content in the current scope.

6.2 Global and Local Variables

The essence of global and local variables lies in their different scopes.
Global variables are declared in the entire py file and can be used globally.
Local variables are declared within a function and can only be used within the function.
 
1 # Example
2 def fun1():
3     name = "aa"
4 print(name)

Cause of Error: Error reported by attempting to access local variables

6.2.1 Local variables have the same name as global variables.

  • Global variables are the same as local variables. Local variables are preferred in functions.
  • Modifying local variables does not affect global variables
 1 name = "bb"
 2 def print_name():
 3     name = "aa"
 4     print(name)
 5      
 6 print_name()
 7 print(name)
 8 # The result of printing is
 9 # aa
10 # bb

6.2.2 global keyword

Using the global keyword: The python compiler is told that the variable is a global variable, not a local variable, so modifying the variable in the body of the function can affect the global.

 1 name = "bb"
 2 def print_name():
 3     global name
 4     name = "aa"
 5     print(name)
 6 print_name()
 7 print(name)
 8 # Printed results:
 9 # aa
10 # aa

6.2.3 nonlocal keywords

Non-local keywords are new keywords in Python 3. They are used to use outer (non-global) variables in functions or other scopes.
nonlocal is suitable for local functions in local functions. It sets the innermost local variables to the exterior local available, but it is not global.
Note: nonlocal must bind local variables
 1 def fun1():
 2     num = 1
 3 
 4     def fun2():
 5         nonlocal num    # Not available here global,Can only be used nonlocal
 6         num += 1
 7         return num
 8     return fun2
 9 
10 
11 aa = fun1()
12 print(aa())

The Nature of Function Names

The function name is essentially the memory address of the function.

7.1 can be cited

1 def func():
2     print('in func')
3 
4 
5 f = func
6 print(f)    # <function func at 0x000001F18D5B2E18>

7.2 Elements that can be considered container types

 1 def f1():
 2     print('f1')
 3 
 4 
 5 def f2():
 6     print('f2')
 7 
 8 
 9 def f3():
10     print('f3')
11 
12 
13 l = [f1, f2, f3]
14 d = {'f1': f1, 'f2': f2, 'f3': f3}
15 # call
16 l[0]()
17 d['f2']()

7.3 can be used as a parameter or return value of a function

7.3.1 as a parameter of function

1 def func1():
2     print("aa")
3 
4 
5 def func2(f2):
6     f2()
7 
8 
9 func2(func1)  # Parameters as functions

7.3.2 as return value

1 def func1():
2 
3     def func2():
4         print("bb")
5     return func2   # As a return value
6 
7 
8 f = func1()    
9 f()

8. Anonymous functions

Syntax format: lambda [parameter 1], [parameter 2],...: [single line expression] or [function call]

1 # No parameters
2 my_fun = lambda : 10 + 20
3 # With parameters
4 my_add = lambda a, b: a + b
5 my_add()
Be careful:
  • The parameters of a function can be multiple, separated by commas.
  • Anonymous functions, however complex, can only write one line and return data directly after the logic has finished.
  • The return value, like a normal function, can be of any data type

 

Anonymous functions do not mean that there must be no name. The variable in front of them is a function name. The reason why it's a function name is that when we look through _name_ we don't have a name. The unification is lambda. There's nothing special when we call it, just like a normal function.
 
Anonymous functions as function parameters
 1 def my_function(func):
 2 
 3     a = 100
 4     b = 200
 5     # hold cucalate_rule Call as a function
 6     result = func(a, b)
 7     print('result:', result)
 8     
 9 
10 my_function(lambda a, b: a + b)

9. Higher Order Functions

9.1 sorted sort

Grammar: sorted(Iterable, key=None, reverse=False)
            Iterable: Iterable Object
            key: Sorting rule (sorted function), in which each object in an iterative object is passed to the parameter of the function and sorted according to the result of the operation of the function.
 1 lst = [5, 7, 6, 12, 1, 13, 9, 18, 5]
 2 # lst.sort()  # sort is the method in the list
 3 # print(lst)
 4 new_lst = sorted(lst, reverse=True)     # Built-in function, return to you a new list,The new list is sorted
 5 print(new_lst)
 6 
 7 
 8 # Sort the list by the length of the string
 9 lst2 = ["Dayang Brother", "Nicholas", "Zhao Si", "Lennon", "Guang Kun", "Shellda Jo"]
10 
11 
12 def func(st):
13     return len(st)
14 
15 
16 new_lst = sorted(lst2, key=func)     # Internally, each element of an iteratable object is passed to func
17 # new_lst = sorted(lst2, key=lambda x: len(x))    # Anonymous functions can also be used
18 print(new_lst)

9.2 filter filtering

Filter: traverse each element in the sequence, determine that each element gets a Boolean value, and if True, leave it behind to form a new iterator
Syntax: filter(function, Iterable) returns an iterator
            Function: A function used for filter ing, in which the elements in iterable are automatically passed to the function, and then the number of data retained is determined by the True or False returned by the function.
            Iterable: Iterable Object
1 list1 = ["1111aaa", "2222aaa", "3333aaa", "4444", "5555", "6666"]
2 list2 = filter(lambda x: x.endswith("aaa"), list1)  # The role of filtration
3 print(list(list2))
4 # Operation results:['1111aaa', '2222aaa', '3333aaa']

9.3 map mapping

    Grammar: map(function, Iterable)
        map processes each element in a sequence and yields a result (an iterator) with the number and location of the iterator elements unchanged
 1 list1 = [1, 2, 3, 4, 5]
 2 list2 = map(lambda x: x+1, list1)  # map The first parameter is a function, and the latter is an iterative object.
 3 print(list(list2))
 4 # Result:[2, 3, 4, 5, 6]
 5 
 6 lst1 = [1, 2, 3, 4, 5]
 7 lst2 = [2, 4, 6, 8, 9]
 8 
 9 
10 print(list(map(lambda x, y: x+y, lst1, lst2)))
11 # Result:[3, 6, 9, 12, 14]

9.4 reduce

reduce processes a sequence and merges it.

from functools import reduce
list1 = [1, 2, 3, 4, 5]
aa = reduce(lambda x, y: x+y, list1)  # The function of the former parameter must be two parameters
print(aa)
# Operation results: 15

 

Posted by Mega on Mon, 09 Sep 2019 02:10:55 -0700