[Python is not a python] function | pass empty statement | lambda anonymous function

I. Function

0x00 What is a function

Functions in Python are widely used.

In the previous chapters, we have been exposed to multiple functions, such as input(), print(), range(), len() functions, etc.,

These are all built-in functions of Python and can be used directly.

In addition to built-in functions that can be used directly, Python also supports custom functions, which define a regular and reusable code as a function, so that it can be written once and called multiple times.

0x01 Give me a chestnut

Earlier, we learned about the len() function. The main function of the len() function is to obtain the length of strings, lists…

We might as well imagine that if there is no len() function, how do we get the length of a string?

Only the simplest ones are considered here to facilitate learning (The author just wants to be lazy)

s = "Hello" # String to be processed
l = 0 # String length variable

for _ in s: # _ means no traversal variables, omit this
    l + = 1 # Accumulated length

print(l)
  

Results of the:

The code runs perfectly, as expected of me, hahaha! (Narcissistic)

You should know that getting the length of a string is a commonly used function and may be used many times in a program. If you write such a repetitive code every time, it will not only be time-consuming and error-prone, but also very troublesome when handing it over to others.

Therefore, Python provides a function that allows us to encapsulate (package) commonly used code in a fixed format into an independent module. As long as you know the name of the module, you can reuse it. This module is called a function.

For example, a piece of code is defined in the program, and this code is used to implement a specific function.

The question is, if we need to implement the same function next time, do we need to copy the previously defined code? It would be silly to do this, as it would mean duplicating the previously defined code every time the program needs to implement that functionality. The correct approach is to define the code that implements a specific function as a function. Every time the program needs to implement the function, it only needs to execute (call) the function.

In fact, the essence of a function is a piece of code that has a specific function and can be reused. This code has been written in advance and given a “nice” name. In the subsequent programming process, if you need the same function, you can call this code directly by giving it a good name.

Next we will learn how to create a function

0x02 Create function

To create a function in python, you need to use the def keyword. The basic rules are as follows:

  • A function code block begins with the def keyword, followed by the function identifier name and parentheses ().
  • Any incoming parameters and arguments must be placed between parentheses. Parameters can be defined between parentheses.
  • The first line of a function can optionally use a docstring – used to store the function description.
  • Function content starts with a colon and is indented.
  • return [expression] Ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.

The basic format is as follows:

def A beautiful function (parameter list): # Yes, Chinese function names are also acceptable
    ... # code block
    return return value #if there is a return value


A beautiful function() # Call function

Next, it’s time for us to show off our skills

Let’s encapsulate the function of getting the string length just now into a function.

def getStrLen(): # Use camelCase notation here
    l = 0 # String length variable
    
    for _ in s: # _ means no traversal variables, omit this
        l + = 1 # Accumulated length
    
    print(l)

Here is accessing the global variable s and printing the length of s

Um, I forgot to call the function…

Let’s look at the built-in len() function and how to get the length of hello

emmm, our getStrLen() is too damn hard to use.

give up! Let’s just stick to the built-in functions.

This chapter ends with flowers! ! !

Hehe, just kidding.

Let’s look at the basic format of the above function. There is a “parameter list” part.

Next, we will use parameter passing to complete our getStrLen() function

0x03 parameter passing

The basic format for defining functions that require passed in parameters is as follows:

def a function that requires passing parameters (parameter name 1, parameter name 2):
    pass # Empty statement

When we call a function that requires passing parameters, we need to fill in the parameters in parentheses:

A function that requires passing parameters (parameter 1, parameter 2)

Parameters are passed one at a time from left to right.

You can also pass parameters like this

A function that requires passing parameters (parameter name 1 = parameter 1, parameter name 2 = parameter 2) #Equivalent to the above parameter passing method

When using parameters in a function, you only need to access the variable

We might as well be bold and not pass in any parameters

Forehead….

In a function that requires parameters, if you do not pass in enough parameters, python will report an error…

That being the case, it’s time to polish up our getStrLen() function.

marvelous

I’m looking at python’s built-in len() function. len() does not print directly, but returns a value.

This value can be used to assign a value to a variable, or it can be printed directly.

If we want to implement this function, we need to use the function return value

0x04.Function return value

It may be a little late for me to say that the function returns a value now, but it has little impact.

We have seen it in the previous basic function format

Now we are reviewing

def func1():
    return 1 # It’s less troublesome to put another one back.

def func2():
    return 1, 2 # Return a tuple

def func3():
    return [1, 2, 3] # Return a list

Function return value is not that difficult

We can now also improve the function just now

def getStrLen(s): # Use camelCase notation here
    l = 0 # String length variable
    
    for _ in s: # _ means no traversal variables, omit this
        l + = 1 # Accumulated length
    
    return l # Return length
    
l = getStrLen("Hello World")
print(l)

We only changed one line in this code: return l

Haha, it’s not that difficult

0x05 Let’s look at parameter passing again

We have briefly talked about parameter passing before, but parameter passing is not as brief as before.

Let me take it out here and talk about it in detail.

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

  • Required parameters
  • keyword arguments
  • Default parameters
  • variable length parameters

emmm….it looks very complicated

Required parameters

Required parameters must be passed into the function in the correct order. The quantity when called must be the same as when declared.

When calling the test() function, you must pass in a parameter, otherwise a syntax error will occur:

def test(a):
    pass

Keyword parameters

Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the values of the parameters passed in.

Using keyword arguments allows a function to be called in a different order than when it was declared, because the Python interpreter is able to match parameter names with parameter values.

The following example uses parameter names when the function test() is called:

def test(a):
    pass

test(a=None)

emmm…. So far, we have used the above method of passing parameters before.

Default parameters

When calling a function, the value of the default parameter is considered the default value if it is not passed in. The following example will print the default age if age is not passed in:

def test(a=1):
    print(a)

test() # If no value of parameter a is passed in, the default value is used.
test(2) #The value of parameter a is 2

Variable length parameters

You may need a function that can handle more arguments than when declared. These parameters are called variable-length parameters. Unlike the above two parameters, they will not be named when declared. The basic syntax is as follows:

def functionname([formal_args,] *var_args_tuple):
    function_suite return [expression]

Variable names with an asterisk (*) will store all unnamed variable parameters. Examples of variable length parameters are as follows:

def test(*a):
    print(a)

test(1, 2, 3)

You can see that parameter a is a tuple

Variable names with double asterisks (**) will store all named variable parameters.

def test(**a):
    print(a)

test(b=1, c=2, d=3)

You can see that parameter a is a dictionary inside.

Our explanation of functions has come to an end.

Ⅱ.pass

0x00 What is pass

To put it simply, pass is a null operation. When the interpreter executes it, it does nothing except check whether the syntax is legal and skips it.

Compared with non-null operations such as return, break, continue and yield, the biggest difference is that it does not change the execution order of the program. It is like a comment we write, except that it occupies a line of code and does not have any impact on the scope in which it is located.

Use of 0x01 pass

pass has no effect, because it is illegal to define an empty loop body, branch structure, or function.

So the role of pass appears at this time.

pass can be used as an empty statement to avoid such syntax errors.

for _ in _:
    pass

while True:
    pass

def a():
    pass

if _:
    pass

That’s all the use of pass.

Ⅲ.lambda anonymous function

0x00 What is an anonymous function

There are two kinds of functions in Python, one is the function defined by def, and the other is the lambda function, which is often called an anonymous function.

In Python, an anonymous function is a function without a defined name.

While the def keyword defines a normal function in Python, the anonymous function lambda is defined using the keyword.

Therefore, anonymous functions are also called lambda functions.

0x01 Give a chestnut

To calculate the square of a number, we use def function and lambd anonymous function respectively.

def sqrt(x):
    return x*x

sqrt1 = lambda x: x*x

It can be seen that lambda is obviously more suitable in this simple function

We can see that using the lambda function first reduces the redundancy of the code. Secondly, using the lambda function eliminates the need to bother naming a function and can quickly implement a certain function. Finally, the lambda function makes the code more readable. Stronger, the program looks more concise.

0x02 lambda syntax

From the simple example above, we can also see that the syntax of the lambda function is unique, and its form is as follows:

lambda argument_list:expersion

The argument_list in the syntax is the parameter list, and its structure is the same as the parameter list of a function in Python, for example

a,b
a=1,b=2
*args
**kwargs
a,b=1,*args
null
....

The expression in the grammar is an expression about parameters. The parameters appearing in the expression need to be defined in argument_list, and the expression can only be a single line. For example, some legal expressions below

1
None
a + b
sum(a)
1 if a >10 else 0
......

The use of 0x03 lambda

(1) Directly assign it to a variable and then call it like a normal function

c=lambda x,y,z:x*y*z
c(2,3,4)

24

Of course, you can also pass actual parameters directly after the function

(lambda x:x**2)(3)
9

(2) Pass the lambda function as a parameter to other functions, such as using it in conjunction with some Python built-in functions such as map, filter, sorted, reduce, etc., as shown below with examples.

fliter(lambda x:x%3==0,[1,2,3,4,5,6])

[3,6]


squares = map(lambda x:x**2,range(5)
print(lsit(squares))
[0,1,4,9,16]

Used in conjunction with the sorted function, for example: creating a list of tuples:

a=[('b',3),('a',2),('d',4),('c',1)]

Sort by first element

sorted(a,key=lambda x:x[0])
[('a',2),('b',3),('c',1),('d',4)]

Sort by second element

sorted(a,key=lambda x:x[1])
[('c',1),('a',2),('b',3),('d',4)]

Used in conjunction with the reduce function

from functools import reduce
print(reduce(lambda a,b:'{},{}'.format(a,b),[1,2,3,4,5,6,7,8,9]))

1,2,3,4,5,6,7,8,9

(3) Nesting uses the lambda function to be nested into a normal function, and the lambda function itself is used as the return value.

def increment(n):
    return lambda x:x + n

f=increment(4)
f(2)
6

(4) String union, there is a default value, you can also use the format x=(lambda…)

x=(lambda x='Boo',y='Too',z='Z00':x + y + z)
print(x('Foo'))

'FooTooZoo'

(5) Define the inline callback function in tkinter

import sys
from tkinter import Button,mainloop

x=Button(text='Press me',command=(lambda :sys.stdout.write('Hello,World\
')))
x.pack()
x.mainloop()

This code is quite interesting, I hope you guys can copy and paste it and run it. (6) Determine whether the string begins with a certain letter

Names = ['Anne', 'Amy', 'Bob', 'David', 'Carrie', 'Barbara', 'Zach']
B_Name= filter(lambda x: x.startswith('B'),Names)
print(B_Name)

['Bob', 'Barbara']

(7) Find the sum of two list elements

a = [1,2,3,4]
b = [5,6,7,8]
print(list(map(lambda x,y:x + y, a,b)))

[6,8,10,12]

(8) Find the length of each word in the string

sentence = "Welcome To Beijing!"
words = sentence.split()
lengths = map(lambda x:len(x),words)
print(list(lengths))
[7,2,8]

emmm, we haven’t talked about most of the rest yet, but it’s okay, just treat it as listening to alien language

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeAdvanced grammarlambda function 382068 people are learning the system