Functions and lambda expressions in python

Posted by Cesar on Wed, 05 Jan 2022 14:23:48 +0100

What is a function

Function refers to "taking" a name for a piece of code that implements a specific function, and then executing (calling) the function through the name
A function can accept zero or more arguments, or return zero or more values

Functions need to be clarified

1. The function needs several key data that need to change dynamically. These data should be defined as the parameters of the function
2. The function needs to send out several important data (that is, the data expected by the caller of the function), which should be defined as the return value
3. Internal implementation process of function

Function definition and calling function

The syntax format of the defined function is as follows:

def Function name (formal parameter list):
	//A function consisting of zero to more executable statements
	[return[Return value]]

python declaration functions must use the def keyword
Function name:
From a syntactic point of view, the function name can only be a legal identifier
From the perspective of program readability, the function name should be composed of one or more meaningful words. The letters of each word are all lowercase, and the words are separated by underscores
Formal parameter list:
It is used to define the parameters that the function can receive. The formal parameter list consists of multiple formal parameter names separated by English commas. Once the formal parameter list is specified when defining the function, the corresponding parameter value must be passed in when calling the function (who calls the function and who is responsible for assigning values to the formal parameters)
Example:

#Define a function and declare two formal parameters
def my_max(x,y):
	#Define a variable z that is equal to the larger of x and y
	z = x if x > y else y
	#Return variable z
	return z
#Define a function and declare a formal parameter
def say_hi(name):
	print("===Executing say_hi()function===")
	return name + ",Hello!"
a = 6
b = 9
#Call my_max() function, assign the return value of the function to the result variable
result = my_max(a,b)
print("result:",result)
#Call say_hi() function, which directly outputs the return value of the function
print(say_hi("xxx"))

Output:

my_ The max() function can be abbreviated as follows:

def my_max(x,y):
#Returns an expression
return x if x > y else y

Provide documentation for functions

That is, write a description document for the function
That is, put a string after the function declaration and before the function body. This string will be used as part of the function. This document is the description document of the function
How to view the function description document:
help() function, through function__ doc__ Attribute access (DOC has two underscores on each side)
Example:

def my_max(x,y):
	'''
	Gets a function with a larger value between two values
	my_max(x,y)
	return x,y The larger number between the two parameters
	'''
	#Define a variable z that is equal to the larger of x and y
	z = x if x > y else y
	#Returns the value of the variable z
	return z 
#Use the help() function to view my_ Help documentation for Max
help(my_max)
print(my_max.__doc__)

Operation results:

Multiple return values

If the program needs multiple return values, you can either wrap multiple values into a list and return them, or you can return multiple values directly
If Python functions directly return multiple values, python will automatically encapsulate multiple return values into meta groups
Example:

def sum_and_avg(list):
	#initialization
	sum = 0
	count = 0
	#Loop through the list
	for e in list:
		#If tuple e is numeric
		if isinstance(e,int) or isinstance(e,float):
			count += 1
			sum += e
		return sum,sum / count
my_list = [20,15,2.8,'a',35,5.9,-1.8]
#Get sum_and_avg function returns multiple values, which are encapsulated into meta groups
tp = sum_and_avg(my_list)
print(tp)

Operation results:

When tp = sum_ and_ When AVG (my_list) calls a function, multiple values returned by the function will be automatically encapsulated into meta groups, so tp seen by the program is a tuple containing two elements (because the called function returns two values)
You can also use the sequence unpacking function provided by python to directly use multiple variables to receive multiple values returned by the function
Example:

s,avg = sum_and_avg(my_list)
print(s)
print(avg)

Recursive function

Calling itself in a function body is called a recursive function
Function recursion contains an implicit loop that repeats a piece of code, but this repetition does not require loop control
For example, the following math problems:
We know a sequence: f(0)=1,f(1)=4,f(n+2)=2*f(n+1)+f(n), where n is an integer greater than 0, find the value of f(10)
Using recursion, a fn() function is defined to calculate the value of f(10)
The procedure is as follows:

def fn(n):
	if n == 0:
		return 1
	elif n == 1:
		return 4
	else:
		#Calling itself in function body is recursive function.
		return 2 * fn(n-1) + fn(n-2)
	#Output the result of fn(10)
	print("fn(10)The results are:",fn(10))

Operation results:

Parameters of function

When defining python functions, you can define formal parameters (formal parameters). The values of these formal parameters can not be determined until they are called. The caller of the function is responsible for passing in parameter values for the formal parameters. In short, who calls the function is responsible for passing in parameter values

keyword parameter

python allows parameter values to be passed in by name when calling a function
The parameters passed in according to the position of the formal parameter are called position parameters. Parameter values must be passed in exactly the order specified when defining the function
If the parameter value is passed in according to the parameter name, the order of defining formal parameters does not need to be observed. This method is called keyword parameter
Example:

#Define a function
def girth(width,height):
	print("width: ",width)
	print("height: ",height)
	return 2 * (width + height)
#In the traditional way of calling functions, parameter values are passed in according to the location
print(girth(3.5,4.8))
#Pass in parameter values based on keyword parameters
print(grith(width = 3.5,height = 4.8))
#Swappable positions when using keyword parameters
print(grith(height = 4.8,width = 3.5))
#Some use keyword parameters and some use location parameters
print(grith(3.5,height = 4.8))

Note: if you want to mix location parameters and keyword parameters, keyword parameters must be after location parameters, that is, only keyword parameters can be after keyword parameters

Parameter defaults

In some cases, the program needs to specify the default value for one or more formal parameters when defining the function, so that when calling the function, you can omit passing in the parameter value for the formal parameter, but directly use the default value of the formal parameter
Syntax format for specifying default values for formal parameters:
Parameter name = Default
Example:

#Specify default values for both parameters
def say_hi(name = "xxx",message = "welcome"):
	print(name,",Hello")
	print("The message is:",message)
#Use default parameters for all
say_hi()
#Only the message parameter uses the default value
say_hi("Baigujing")
#Neither parameter uses the default value
say_hi("Baigujing","Welcome to study")
#Only the name parameter uses the default value
say_hi(message = "Welcome to study")

Operation results:

As mentioned above, if only one location parameter is passed in, because the parameter is in the first place, the system will pass the function value to the name parameter. Therefore, we cannot call say as follows_ Hi() function
say_hi("welcome to learn")
The "welcome to learn" string passed in during the above call will be passed to the name parameter instead of the massage parameter
It can't be like this: say_hi(name = "Baigujing", "welcome to learn")
Because python stipulates that keyword parameters must be after positional parameters
It can't be like this: say_hi("welcome to learn", "Baigujing")
Because the first string does not specify a keyword parameter, the location parameter will be used to pass in the parameter value for the name parameter, and the second parameter will use the keyword parameter to pass in the parameter value for the name parameter again, which means that both parameter values will actually be passed to the name parameter, and the program has passed in multiple parameter values for the name parameter
It can be in the following two forms:

say_hi("Baigujing",message = "Welcome to study")
say_hi(name = "Baigujing",message = "Welcome to study")

Because python requires that the keyword parameter must be after the positional parameter when calling the function, the parameter (keyword parameter) that specifies the default value when defining the function must be after the parameter without the default value
Example:

#Define a function to print triangles. Parameters with default values must be placed later
def printTriangle(char,height = 5):
	for i in range(1,height + 1):
		#Print a row of spaces first
		for j in range(height - i):
			print('',end = '')
		#Print another row of special characters
		for j in range(2 * i - 1):
			print(char,end = '')
		print()
printTriangle('@',6)
printTriangle('#',height = 7)
printTriangle(char = '*')

Operation results:

A printTriangle() function is defined. The first char parameter of the function has no default value, and the second height parameter has a default value
When printTriangle() is called for the first time, the program uses two location parameters, char and height, to pass in parameter values
When printTriangle() is called the second time, the first parameter uses the location parameter, and the parameter value will be passed to the char parameter. The second parameter uses the keyword parameter to pass in the parameter value for the height parameter
When printTriangle() is called for the third time, only the keyword parameter is used to pass in the parameter value for the char parameter. At this time, the height parameter will use the default value

Parameter mobile phone (variable number of parameters)

python allows an asterisk (*) before a formal parameter, which means that the parameter can receive multiple parameter values, which are passed in as tuples
Example:

#Defines functions that support parameter collection
def test(a,*books):
	print(books)
	#books are treated as tuples
	for b in books:
		print(b)
	#Output the value of integer variable a
	print(a)
#Call the test() function
test(5,"python book","well python course")

Operation results:

When the test() function is called, the books parameter can pass in multiple strings as parameter values. From the function body code of test(), the essence of parameter collection is a tuple: python will collect multiple values passed to books parameters into a tuple

python can collect keyword parameters and integrate them into a dictionary
In order for python to collect keyword parameters, you need to precede the parameters with two asterisks
In this case, a function can contain both a parameter that supports "normal" parameter collection and a parameter that supports keyword parameter collection
Example:

#Defines functions that support parameter collection
def test(x,y,z=3,*books,**scores):
	print(x,y,z)
	print(books)
	print(scores)
test(1,2,3,"study","handout",language=89,mathematics=94)

Operation results:

When the above program calls the test() function, the previous 1, 2 and 3 will be passed to the ordinary parameters x, y and z
The next two strings will be collected into meta groups by the books parameter
The last two keyword parameters will be collected into a dictionary
For the test() function defined in the above way, the default value of parameter z has little effect
If you debug like this
test(1,2, "learning", "handouts", Chinese = 89, mathematics = 94)
1,2, "learning" is passed to x,y,z
"Handout" to books
The last two are passed to scores

If you want the default value of the z parameter to work, you need to pass in only two positional parameters
Example:
test(1,2, Chinese = 89, mathematics = 94)
In this way, 1 and 2 are passed to X and Y. at this time, the z parameter will use the default parameter value of 3
The books parameter will be an empty tuple
The last two keyword parameters will be collected into a dictionary
Operation results:

Reverse parameter collection

On the premise that the program has list, tuple, dictionary and other objects, their elements are "disassembled" and passed to the parameters of the function
For reverse parameter collection, you need to add an asterisk before the incoming list and tuple parameters and two asterisks before the dictionary parameters
Example:

def test(name,message):
	print("The user is:",name)
	print("Welcome message:",message)
my_list = ['xxx','Welcome to study']
test(*my_list)

Operation results:

The above code first defines a function that requires two parameters, my in the program_ The list contains two elements to make my_ The two elements of the list are passed to the test() function, and the program passes in my_ An asterisk is added before the list parameter
In fact, even for parameters that support collection, if the program needs to pass a tuple to the parameter, it also needs to use reverse collection
Example:

def foo(name,*nums):
	print("name Parameters:",name)
	print("nums Parameters:",nums)
my_tuple = (1,2,3)
#Using reverse collection, set my_ The tuple element is passed to the num parameter
foo('fkit',*my_tuple)

Operation results:

Parameter transfer mechanism of function

The parameter transfer mechanism of functions in python is "value transfer", that is, a copy (Replica) of the actual parameter value is passed into the function, and the parameters themselves will not be affected
Example:

def swap(a,b):
	#The following code implements the value exchange of a and B variables
	a,b = b,a
	print("stay swap In the function, a The value of is",a,";b The value of is",b)
a = 6 
b = 9
swap(a,b)
sprint("After the exchange, a The value of is",a,";b The value of is",b)

Operation results:

From the running results, in the swap() function, the values of a and b are 9 and 6 respectively. After the exchange, the values of variables A and b are still 6 and 9
The variables A and b actually defined in the program are not a and b in the swap() function. A and b in the swap() function are just copies of variables A and b in the main program

Variable scope

When a variable is defined in a program, the variable has a scope, and the scope of the variable is called its scope
According to the location of the defined variable, there are two types of variables:
1. Local variables: variables defined in a function, including parameters, are called local variables
2. Global variables: variables defined outside the function and within the global scope are called global variables
During the execution of each function, the system will allocate a "temporary memory space" for the function, and all local variables are saved in this temporary memory space. When the function is executed, this memory space will be released, and these local variables will become invalid, so you can't access local variables after leaving the function
Global variables mean that they can be accessed within all functions
python provides three function tools to obtain the "variable dictionary" within the specified range
1. globals(): this function returns the "variable dictionary" composed of all variables in the global scope
2. locals(): this function returns the "variable dictionary" composed of all variables in the current local range
3. vars(object): get the "variable dictionary" composed of all variables within the specified object range. If the object parameter is not passed in, the functions of vars() and locals() are exactly the same

Topics: Python Lambda Functional Programming