[Python Programming] function definition, call, parameter transfer and Application

Posted by moehome on Tue, 25 Jan 2022 02:14:01 +0100

10. Definition, call, parameter transfer and application of [Python Programming] function

Note: this tutorial mainly uses Python 3 6 programming on jupyter notebook. Python environment configuration reference [Python learning] start your Anaconda installation and python environment management with windows 10 perhaps [Python learning] start your Anaconda installation and python environment management with pure terminal command.

10.1 function definition and call

Mathematical definition

Mathematically, the function is defined as: given A number set A, assuming that the element in it is x, apply the corresponding rule f to the element X in A and record it as f (x), so as to obtain another number set B. assuming that the element in B is y, the equivalent relationship between y and X can be expressed as y=f (x).
The concept of function contains three elements: definition domain A, value domain B and correspondence rule f. The core is the correspondence rule f, which is the essential feature of functional relationship.
In our junior high school and senior high school, there are univariate primary function, univariate quadratic function, trigonometric function, exponential function and logarithmic function.

Programming definition

In computer science, functions are organized and reusable code segments used to realize single or associated functions. Function can improve the modularity of application and the reuse rate of code.

Whether in mathematics or computer science, functions include input (independent variables), processing code (processing rules), and output (dependent variables).

In python, you can define a function that you want to function. The following are simple rules:

  • The function code block starts with the def keyword, followed by the function identifier name and parentheses ().
  • Any incoming parameters and arguments must be placed between parentheses, which can be used to define parameters.
  • The first line of the function can optionally use a document string - used to hold the function description.
  • The function content starts with a colon: and is indented.
  • Return [expression] ends the function and selectively returns a value to the caller. A return without an expression is equivalent to returning None.
  • By default, parameter values and parameter names match in the order defined in the function declaration.

Its format is:

def Function name (parameter list):
    Function body
    return Return results

For example:

  • Using python to realize the unary function in Mathematics
# y = 2x+1
def f1(x):
    y = 2*x + 1
    return y
# Try using this function to calculate the y value when x=5:
print("f1(5)=", f1(5)) # Call f1 function
f1(5)= 11
  • Using python to realize univariate quadratic function in Mathematics
# y=2x^2+3x-9
def f2(x):
    y=2*x**2+3*x-9
    return y
# Try using this function to calculate the y value when x=5:
print("f2(5)=", f2(5)) # Call f2 function
f2(5)= 56
  • Use python to input the radius to calculate the area and perimeter of the circle
import math
# Calculate the area of a circle
def cal_area_of_circle(r):
    s = math.pi*r*r
    return s
# Calculate the circumference of a circle
def cal_circumference_of_circle(r):
    c = 2*math.pi*r
    return c

# Test function
r = float(input("Please enter the radius of the circle(cm): "))
print("The radius of the circle is:", r)
print("The area of the circle is:", cal_area_of_circle(r))
print("The circumference of the circle is:", cal_circumference_of_circle(r))
Please enter the radius of the circle(cm): 5
 The radius of the circle is: 5.0
 The area of the circle is 78.53981633974483
 The circumference of the circle is 31.41592653589793

10.2 parameters and parameter transfer

In python, function parameters, strictly speaking, have no type, that is, they can be passed to any type of object. You can usually constrain the type of object you want to pass in, or judge the type of object inside a function.

In python, a type belongs to an object, and a variable has no type. Among the six standard data types of python 3:

  • Immutable types (3): Number, String, Tuple
  • Variable types (3): List, Dictionary, Set

Explanation: everything in python is an object. Strictly speaking, we can't say whether to pass values or references. We should say to pass immutable objects and variable objects.

python passes immutable object instances

  • Immutable type: similar to the value transfer in C + +, the variable is assigned x=5 and then x=10. In fact, an int value object 10 is newly generated and X points to it, while 5 is discarded. Instead of changing the value of X, it is equivalent to newly generated X.
    Before and after calling the function, the formal parameter and the actual parameter point to the same object (the object id is the same). After modifying the formal parameter inside the function, the formal parameter points to a different id.
# Verify the assignment of variables of immutable type
x = 5
id1 = id(x)
print(id1)
x = 10
id2 = id(x)
print(id2)
print(id1 == id2)
94347800181568
94347800181728
False
# python passes immutable objects, which are modified in the function and will not affect the object value outside the function
def change(x):
    # The symbol x inside the function represents the formal parameter
    print("Formal parameters inside a function x of id=", id(x))   # Parameter and argument point to the same object
    x=2022
    print("Formal parameters after internal re assignment of function x of id=", id(x))  # The formal parameter points to a new object

print("-----------When x When is numeric type------------------")
x=2021
print("x The types of are:",type(x))
print("Argument x Value of=", x)
print("Arguments to the passed in function x of id=", id(x))
change(x)
print("Argument x Value of=", x)
-----------When x When is numeric type------------------
x The type of is: <class 'int'>
Argument x Value of= 2021
 Arguments to the passed in function x of id= 140642597090288
 Formal parameters inside a function x of id= 140642597090288
 Formal parameters after internal re assignment of function x of id= 140642597089840
 Argument x Value of= 2021

python passing variable object instances

  • Variable type: similar to the reference passing of C + +. If the variable is assigned list1=[1,2,3,4] and then list1[2]=5, the value of the third element of list1 will be changed. list1 itself does not move, but some of its internal values have been modified.
# Verify the assignment of variable types
list1=[1,2,3,4]
id3 = id(list1)
print(id3)
list1[2] = 5
id4 = id(list1)
print(id4)
print(id3 == id4)
140642597025800
140642597025800
True
# python passes variable objects. Modifying them inside a function will affect the object value outside the function
def change(x):
    # The symbol x inside the function represents the formal parameter
    print("Formal parameters inside a function x of id=", id(x))   # Parameter and argument point to the same object
    x.append(2022) # The passed in function uses the same reference as the object that adds new content at the end of the list.
    print("Function internal modified list parameters x of id=", id(x))  # The formal parameter points to a new object

print("-----------When x When is a list type------------------")
x=[2019,2020,2021]
print("x The type of is:",type(x))
print("Argument x Value of=", x)
print("Arguments to the passed in function x of id=", id(x))
change(x)
print("Argument x Value of=", x)
-----------When x When is a list type------------------
x The type of is: <class 'list'>
Argument x Value of= [2019, 2020, 2021]
Arguments to the passed in function x of id= 140642614321416
 Formal parameters inside a function x of id= 140642614321416
 Formal parameters after modifying the list inside the function x of id= 140642614321416
 Argument x Value of= [2019, 2020, 2021, 2022]

Parameter type

The following are the formal parameter types that can be used when calling a function:

  • Required parameters: required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.
  • Keyword parameters: function calls use keyword parameters to determine the passed in parameter values. Using keyword parameters allows the order of parameters when calling a function to be inconsistent with that when declared, because the Python interpreter can match parameter values with parameter names.
  • Default parameters: when calling a function, if no parameters are passed, the default parameters will be used.
  • Variable length parameters: you may need a function that can handle more parameters than you originally declared. These parameters are called indefinite length parameters and will not be named when declared.
  • Parameters marked with an asterisk * will be imported as tuples to store all unnamed variable parameters.
def functionname([formal_args,] *var_args_tuple ):
    "function_Document string"
    function_suite
    return [expression]
  • Parameters with two asterisks * * will be imported in the form of a dictionary.
def functionname([formal_args,] **var_args_dict ):
    "function_Document string"
    function_suite
    return [expression]
  • When declaring a function, the asterisk * in the parameter can appear separately. If the asterisk * appears separately, the parameter after the asterisk * must be passed in with a keyword.
# r in the following example is the required parameter
def cal_area_of_circle(r):
    s = math.pi*r*r
    return s
# A and B of the following example are required parameters
def cal_area(a,b):
    '''Calculate the area of the matrix
    '''
    s = a*b
    return s
print(cal_area(1,3))
#print(cal_area(1))
'''
implement cal_area(1)
report errors: TypeError: cal_area() missing 1 required positional argument: 'b'
'''
# The following form is the keyword parameter. The function call uses the keyword parameter to determine the passed in parameter value.
print(cal_area(a=1,b=3))
print(cal_area(b=3,a=3))
3
3
9
# A and B of the following example specify the default parameters
def cal_area_v2(a=7,b=8):
    '''Calculate the area of the matrix
    '''
    s = a*b
    return s
# If no a and b parameters are passed in the instance, the default parameters are used
print(cal_area_v2())
print(cal_area_v2(3))
print(cal_area_v2(5))
print(cal_area_v2(b=3))
56
24
40
21
# The following example is an indefinite length parameter
def printinfo(exp_name, *vartuple):
    "Print any incoming parameters"
    print("output: ")
    print(exp_name)
    print(vartuple)
    
printinfo('exp1', [1,2,3,4], 50,"Hello world!")
output: 
exp1
([1, 2, 3, 4], 50, 'Hello world!')
# The following example is an indefinite length parameter
def printinfo( arg1, **vardict ):
    "Print any incoming parameters"
    print("output: ")
    print(arg1)
    print(vardict)

# Call the printinfo function
printinfo(1,a=2,b=3)
output: 
1
{'a': 2, 'b': 3}
def f(a,b,*,c):
    return a*b*c

print(f(1,2,c=3)) # Correct calling method

#print(f(1,2,3))
'''
print(f(1,2,3))
report errors: TypeError: f() takes 2 positional arguments but 3 were given
'''
6





'\nprint(f(1,2,3))\n report errors: TypeError: f() takes 2 positional arguments but 3 were given\n'

10.3 creating anonymous functions with lambda expressions

The so-called anonymity means that a function is no longer defined in the standard form of def statement. Its format is:

lambda [arg1 [,arg2,.....argn]]:expression

explain:

  • lambda is just an expression, and the function body is much simpler than def.
  • The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.
  • lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace.
  • Although lambda function can only write one line, it is not equivalent to C or C + + inline function. The purpose of the latter is to call small functions without occupying stack memory, so as to increase operation efficiency.

Application scenario of lambda function:

  • Assign a lambda function to a variable, and call the lambda function indirectly through this variable.
  • Assign a lambda function to another function to replace the other functions with the lambda function.
  • Pass lambda functions as arguments to other functions. Some Python built-in functions accept functions as parameters. Typical built-in functions include filter function, sorted function, map function and reduce function.
# lambda can simplify the function description into one line of code
def f(x):
    return x**2
print(f(4))

g = lambda x:x**2
print(g(4))
16
16
# Sorts the list in ascending order of its absolute value size
list1 = [9,-2,6,-5]
list2 = sorted(list1,key=lambda x:abs(x))
print(list2)
[-2, -5, 6, 9]
# Filter out even values in the list
list3 = [1,2,3,4,5,6,7,8,9]
list4 = [i for i in filter(lambda x: x % 2 == 0, list3)]
print(list4)
[2, 4, 6, 8]
# Add 1 to the elements in the list
list5 = [1,2,3,4,5]
list6 = [i for i in map(lambda x: x+1, list5)]
print(list6)
[2, 3, 4, 5, 6]
# Save the anonymous function in the value position of the dictionary
func_dict={'2':(lambda x: x * 2),
           '3':(lambda x: x * 3),
           '4':(lambda x: x * 4)
          }
print(func_dict["2"](3)) # Calculate the power of 3
print(func_dict["3"](3)) # Calculate the third power of 3
6
9

Topics: Python Lambda function