Python(day.5 function and Lambda expression)

Keywords: Programming Lambda Python Asterisk

function

To create a function, the keyword del is used, followed by a colon and its executor.

>>>del MyFirstFunction():
		print('hello')
		print('world')
		print('!')
>>>MyFirstFunction()
hello
world
!

Parameters of function

When calling a function, the parameter position should be assigned. There should not be too many parameters to define the function. Three to four are appropriate.

>>>del MySecondFunction(name):
		print(name + 'Hello')
>>>MySecondFunction('moshengren')
moshengren Hello

Formal and actual parameters

Function document

>>>del MyFirstFunction(name):
	'In the process of function definition name Formal reference'
	#Because it's just a form that represents the position of a parameter.
	print('Passed in'+name+'It's called an argument, because it's a specific parameter value.')

Where, the single quotation mark part is the function document, which can be called with myfirstfunction.

MyFirstFunction('moshengren')

The moshengren passed in is an argument because it is a specific parameter value.

Return value of function

return

>>>del add(num1,num2):
		return (num1+num2)
>>>print(add(5,6))
11

Key parameters

>>>del SaySome(name,words):
		print(name + '->' + words)
>>>Saysome ('little Turtle ',' let programming change the world! )
Little Turtle - > let programming change the world!
>>>Saysome ('Let programming change the world! ',' Little Turtle ')
Let programming change the world! > small turtle
 >>>Saysome (words = 'let programming change the world! , name = 'Little Turtle')
Little Turtle - > let programming change the world!

With keywords, Python does not index parameters in order, but in terms of keywords.

Default parameters

Is a parameter that defines a default value. At this time, the function can run normally without parameters.
The key parameter specifies the parameter to be assigned through the parameter name when the parameter is called; the default parameter is to assign the initial value to the parameter during the parameter definition process.

Collection parameters (variable parameters)

Since you don't know how many parameters are needed at the beginning of creating a function, you need to create a tuple and pack it into groups and put it in the parameter with asterisk; at this time, you only need to add asterisk before the parameter; however, it is worth noting that if you want to add other fixed value parameters after the collected parameters, you need to use the keyword parameter to set the value when calling the function, otherwise the later parameters will be Listed as the category of collection parameters.

>>>def test(*params):
		print('the length of the parameter is: ', len(params));
		print('the second parameter is: ', params[1]);
>>>Test (1, 'Little Turtle', 3.14,5,6,7,8)
The length of the parameter is: 7
 The second parameter is: small turtle
>>>def test(*params,exp):
		print('the length of the parameter is: ', len(params),exp);
		print('the second parameter is: ', params[1]);
>>>Test (1, 'Little Turtle', 3.14,5,6,7,exp=8)
The length of the parameter is: 6 8
 The second parameter is: small turtle

Or change the parameter after the collection parameter to the default parameter.

Functions and procedures

>>>def hello():
		print('hello world!')
>>>temp hello()
hello world!

If temp is called at this time, print (Temp) will not work.

>>>def back():
		return [1,'Little Turtle',3.14]
>>>back()
[1,'Little Turtle',3.14]

When Python returns multiple values, it can choose the list; when it does not package the list, it will return the tuple by default.

Scope of function variable

Local variable, global variable.

def discounts(price,rate):
	final_price=price*rate
	return final_price
old_price=float(input('Please enter the original price:'))
rate=float(input('Please enter discount rate:'))
new_price=discounts(old_price,rate)
print('The discounted price is:',new_price)

Price, rate and final price are all local variables. Old price, rate and new price are global variables.
Global variables can also be used if they are not defined before the definition.

Embedded functions and closures

I. global keyword

>>>count=5
>>>def MyFun():
		global count
		count=10
		print(10)
>>>MyFun()
10
>>>print(count)
10

Embedded function

>>>def fun1():
		print('fun1()Being called...')
		def fun2():
			print('fun2()Being called...')
		fun2()#This line belongs to fun1 and calls fun2.
>>>fun1()
fun1()Being called...
fun2()Being called...

Three, closure
An important syntax structure of functional programming.
Definition: if a variable in an internal function is referenced in an external scope, the internal function is called a closure.

>>>def FunX(x):
		def FunY9Y0;
			return x*y
		return FunY
>>>FunX(8)(5)
40
>>>i=FunX(8)#Or it can
>>>i(5)
40

Either way.
Note: internal functions in a closure cannot be called directly outside.

>>>def Fun1():
		x=5
		def Fun2():
				x*=x
				return x
		return Fun2()
>>>Fun1()#An error is reported because the x in Fun2() is equivalent to an undefined local variable
>>>def Fun1():
		x=[5]
		def Fun2():
				x[0]*=x[0]
		return Fun2()
>>>Fun1()
25#At this time, it runs successfully, because the list does not belong to the category of stack and can save data.
>>>def Fun1():
		x=5
		def Fun2():
				nonlocal x
				x*=x
				return x
		return Fun2()
>>>Fun1()

Defining a non local keyword can explain that x is not a local variable.

Lambda expression

Basic syntax: before the colon is the parameter of the original function, and after the colon is the return value of the function.

>>>g=lambda x:2*x+1
>>>g(5)
11

The following example shows how to call this expression when there are multiple parameters.

>>>def add(x,y):
		return x+y
>>>add(3,4)
7
>>>g=lambda x,y:x+y
>>>g(3,4)
7

lambda expression functions:
1. You can save the process of defining functions. Just write a simple script to manage the server time. You don't need to define a function specifically and then call it.
2. For some abstract functions that only need to be called once or twice after the whole program is executed, the use of this expression does not need to consider the problem of naming.
3. Simplify code readability.

Two strong BIF

1.filter()
Start the filtering function and filter out the non True content.
If all even numbers are filtered out:

>>>de odd(x):
		return x%2
>>>temp=range(10)
>>>show=filter(odd,temp)
>>>list(show)
[1,3,5,7,9]
>>>list(filter(lambda x:x%2,range(10)))
[1,3,5,7,9]

2.map()
The effect is the same as that of filter().

>>>list(map(lambda x: x*2,range(10)))
[0,2,4,6,8,10,12,14,16,18]

Posted by designxperts on Sat, 26 Oct 2019 08:08:38 -0700