Functions in python

Functions in python###

1. Create a parameterless function#

Def is the keyword for creating a function, and calling a function is the function name with parentheses.

def MYFirstFunction():print('This is the first function created')print('I said it was very cold. . . . .')

# Call functions
MYFirstFunction()

# operation result:
This is the first function created
I said it was very cold. . . . .

2. Create a function with one parameter#

The actual parameters passed in from the following code are inconsistent, and we can see that the results are different.

def MYSecondFunction(name):print('welcome'+name +'Come to my python function.')MYSecondFunction('Zhang San')MYSecondFunction('Li Si')MYSecondFunction('Wang Wu')

# operation result:
Welcome Zhang San to my python function.
Welcome Li Si to my python function.
Welcome Wang Wu to my python function.

3. Create a function with multiple parameters#

The following code defines two functions, each of which has two formal parameters. The first add function is called, assigned directly, and the information is printed out. The add1 function is called using print, but there is a built-in BIF function return in the code to return to add1, so the information can be printed out using print.

def add(num1,num2):
 suum = num1 + num2
 print('The calculation results are as follows:')print(suum)

def add1(num1,num2):return(num1 + num2)add(999,150)print(add1(7,8))

# The results are as follows:
The calculation results are as follows:
114915

4. Some nouns in functions#

4.1 Formal parameters, actual parameters, function documentation##

Formal parameters: the parameters in parentheses after the name of the defined function are called formal parameters (parameter)
Argument: The parameter passed in when the function is called is the argument.
Function documentation: In the process of writing a function, if the code body is large, it is convenient for others to quickly identify the code.

def MyFUN(name):'The name in the function definition process is called a formal parameter'
 # Think that ta is just a form, meaning that it occupies a parameter position
 print('Passed in'+ name +'It is called an actual parameter, because Ta is a specific parameter value!')MyFUN('Zhang San')print(MyFUN.__doc__)print(help(MyFUN))

# The results are as follows:
The Zhang San passed in is called the actual parameter, because Ta is the specific parameter value!
The name in the function definition process is called a formal parameter
Help on function MyFUN in module __main__:MyFUN(name)
 The name in the function definition process is called a formal parameter

None

4.2 Keyword parameters and default parameters##

Keyword parameter: Defined when calling the function, assign value by parameter name, for example: MyFUN(name='张三')
Default parameter: The parameter that defines the default value is called the default parameter, and the assignment becomes the default parameter in the process of function definition parameter.

def animal(name='monkey',action='Tree climbing'):print(name +'like'+ action)animal()animal('Swim','duck')animal(action='Swim',name='duck')

# The results are as follows:
Monkeys like to climb trees
Swimming like ducks
Ducks like swimming

4.3 Collect parameters##

Collecting parameters: Add an * sign in front of the formal parameters to represent the collection parameters. Multiple parameters can be collected, for example: MyFUN(*name) In fact, python sets the formal parameter name of the collection parameter to a tuple, and then calls the actual parameter from this tuple. If a function has other parameters in addition to the collection parameters, please set this parameter as the default parameter. If you do not set the default parameter, the function will report an error, and all actual parameters will be defaulted to the collection parameter.

def  add(*num,mon='Gorilla'):print('The length of the collected parameters of this function is:',len(num))print('The second parameter is:',num[2])print('The default parameters of this function are:'+ mon)add('White rabbit','little turtle','Elephant','hippo','leopard',mon ='monkey')

# The results are as follows;
The length of the collected parameters of this function is: 5
The second parameter is: elephant
The default parameter of this function is: monkey

5. Functions and procedures#

In programming languages, we think that the function function has a return value, while the procedure procedure is simple, special and has no return value.
'Python has only functions and no processes', why do you say that? For example, we define a function and print a hello and word as follows:

def hello():print('Hello,word!')

temp =hello()print(temp)print(type(temp))

# The results are as follows:
Hello,word!
None
< class'NoneType'>

Python can return multiple values. We can think of a list. The use of commas in the list can become a tuple. In the following example, we can see that the return in python packs this set of data into one data to return.

def MyFun():return[1,'list','done']print(MyFun())

def MyFun1():return1,'list','done'print(MyFun1())

# The results are as follows:
[1,' list','done'](1,'list','done')

6. Global variables and local variables#

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 the discount rate:'))
new_price =discounts(old_price,rate)print('The discounted price is:',new_price)print('Here is trying to print the local variable final_The value of price:', final_price )

# The results are as follows:

Please enter the original price: 100
Please enter the discount rate: 0.8
The discounted price is: 80.0Traceback(most recent call last):
 File "D:/Backup/PyCharm/study_py.py", line 25,in<module>print('Here is trying to print the local variable final_The value of price:', final_price )
NameError: name 'final_price' is not defined

From the example sheet above, it is not difficult to find that when we print the local variables, an error is reported, and the final_price is not defined. That is to say, the final_price we defined is only valid in the discounts function. When this function comes out, this variable is invalid. In fact, when python calls the function, it will store these codes in the stack and run a code. This code will be deleted from the stack space. In the above code, old_price and new_price are global variables. They have greater authority than local variables. Its scope is the entire code, the real module, but we should also pay attention when modifying global variables. If it is inside the function Modify the global variable, python will create a local variable that is the same as the global variable, such as old_price in the following example:

def discounts(price,rate):
 final_price = price * rate
 old_price =50print('Here is an attempt to print the modified variable old_The value of price:', old_price )return final_price
old_price =float(input('Please enter the original price:'))
rate =float(input('Please enter the discount rate:'))
new_price =discounts(old_price,rate)print('The discounted price is:',new_price)print('Here is an attempt to print the modified global variable old_The value of price:', old_price )

# The results are as follows:
Please enter the original price: 100
Please enter the discount rate: 0.8
Here is an attempt to print the modified variable old_The value of price: 50
The discounted price is: 80.0
Here is an attempt to print the modified global variable old_The value of price: 100.0

Global variables can be accessed inside the function, but we should not try to modify a global variable, because python will use shielding shadowing to protect global variables, how to protect it?
Python will create a variable that is the same as a global variable and set it as a local variable. But if we want to modify global variables, can it be achieved? The answer is yes. We need to use the global keyword, for example, as follows:

count =5
def MyFUN():
 count =10print(count)MyFUN()print(count)

# The results are as follows:
105

# We can add the global keyword to the test:
count =5
def MyFUN():
 global count
 count =10print(count)MyFUN()print(count)

# The results are as follows:
1010

7. Inline functions and closures#

7.1 Built-in function##

In fact, functions in python can also be defined internally. We can call them embedded functions or internal functions. What we need to pay attention to is that the scope of internal functions is within external functions. In other words, the Fun2 function takes effect inside the Fun1 function. If you leave the Fun1 function, the Fun2 function will not take effect. Let me give you an example

def Fun1():print('Fun1 is being called')
 def Fun2():print('Fun2 is being called')Fun2()Fun1()

# The results are as follows:
Fun1 is being called
Fun2 is being called

7.2 Closure##

The closure in python is defined in form as if an internal function references a variable in the external scope (but not in the global scope), then the internal function will be considered a closure.

def Funx(x):
 def Funy(y):return x * y
 return Funy 
 # Return Funy pay attention here, because almost everything in our python is an object, we say that you can remember his name in python, you don’t need to remember what data, type or variable it is, we can directly The function object is returned directly.
i =Funx(8)print(i)print(type(i))print(i(5))print(Funx(8)(5))print(Funy(5))

# The results are as follows:
< function Funx.<locals>.Funy at 0x0355B610><class'function'>4040Traceback(most recent call last):
 File "D:/Backup/PyCharm/study_py.py", line 54,in<module>print(Funy(5))
NameError: name 'Funy' is not defined
# Let&#39;s understand the concept of closure. If in an internal function, for Funx, Funy belongs to the internal function; for the external scope, the external scope of this function Funy is the variable x of the entire function space of Funx to reference it. . When these two points are reached, we will say that this Funy is a closure.
def Fun1():
 x =5
 def Fun2():
  x *= x
  return x
 returnFun2()Fun1()

# The results are as follows:
Traceback(most recent call last):
 File "D:/Backup/PyCharm/study_py.py", line 63,in<module>Fun1()
 File "D:/Backup/PyCharm/study_py.py", line 62,in Fun1
 returnFun2()
 File "D:/Backup/PyCharm/study_py.py", line 60,in Fun2
 x *= x
UnboundLocalError: local variable 'x' referenced before assignment

Note: UnboundLocalError: local variable'x' referenced before assignment** The reason for this error is: because when the return Fun2() is executed, then he will run to Fun2 to execute, the entire internal space of Fun1, x=5, it belongs to the global variable in Fun2, but for the entire code, it is a local variable, in fact, x=5 is an external variable that is not a global variable; x in Fun2 and x in Fun1 are not a variable, As mentioned in the previous global variables and local variables, define a global variable in the python function. Python shields this global variable through shadowing, creating a variable x that is the same as the global variable, but this x is a local variable , Which means that x=5 in Fun1 is not passed into Fun2, and this x in Fun2 is a local variable. **

If we want to pass the x in Fun1 to Fun2, we can set this parameter in Fun2 to x, and the square of x can be achieved as shown in the figure below.

def Fun1():
 x =5
 def Fun2(x):
  x *= x
  return x
 returnFun2(x)print(Fun1())

In python2,

def Fun1():
 x =[5]
 def Fun2():
  x[0]*= x[0]return x[0]returnFun2()print(Fun1())

# The results are as follows:
25

In the world of python3, another keyword nonlocal was invented. This keyword is used in the same way as the global keyword. Set the x variable in Fun1 to be directly referenced in Fun2.

def Fun1():
 x =5
 def Fun2():
  nonlocal x
  x *= x
  return x
 returnFun2()print(Fun1())

# The results are as follows:
25

8. lambda expression#

8.1 lambda expression##

Lambda functions are also called anonymous functions. An anonymous function is a function without a name. What about a function without a name? Of course. If some functions are only used temporarily and their business logic is very simple, there is no need to give them a name.

When writing some execution scripts in python, using lambda can save the process of defining functions. For example, if we just need to write a simple script to manage server time, we don’t need to define a function specifically, and then write and call, just use lambda. Make the code more streamlined
For some functions that are more abstract and only need to be called once or twice after the entire program is executed, sometimes naming the function is a headache. Using lambda does not need to consider the naming problem.
Simplify the readability of the code, because the reading of ordinary diaosi functions often needs to be transferred to the beginning of the def definition part, using lambda functions can save such steps.

def  Fun(x):return x *2+ x
print(Fun(5))

# The results are as follows:
15

g = lambda x : x *2+ x
print(g(5))

# The results are as follows:
15

# From the above results, we can see that the results of the two pieces of code are the same, and lambda can simplify the amount of code.

8.2 Python built-in BIF: filter function##

filter() filter. The filter() function is used to filter the sequence, filter out the elements that do not meet the conditions, and return an iterator object. If you want to convert to a list, you can use list() to convert.

It should receive two parameters, the first is a function, and the second is a sequence. Each element of the sequence is passed as a parameter to the function for judgment, and then it returns True or False. Finally, the element that returns True is placed in the new list. Let's give an example:

print(filter(None,[0,1,False,True]))print(list(filter(None,[0,1,False,True])))

# The results are as follows. Through the following results, we can see that the filter function can filter out the previous None and print out a new list.
< filter object at 0x0345D0D0>[1, True]

# Write a list of 0 to 9 and remove the odd numbers

def odd(x):return  x %2

temp =range(10)

show =filter(odd,temp)print(list(show))

# The results are as follows:
[1,3,5,7,9]

# We can see that a function is defined above, and there are more codes. If lambda expressions have been used, let’s take a look

print(list(filter(lambda x : x %2,range(10))))

# The result is:
[1,3,5,7,9]

# You can see that using lambda expressions we can get a line of code, which is very beautiful for python.

8.3 Python built-in BIF: map function##

map() will map the specified sequence according to the provided function.

The first parameter function calls the function function with each element in the parameter sequence and returns a new list containing the return value of each function function.

print(list(map(lambda x : x * x ,range(5))))

# The results are as follows:

[0,1,4,9,16]

9. Recursion#

What is recursion? Recursion is to call one's own function inside a function, which is called recursion.

The sys module can be called in python, sys.setrecursionlimit(100) #You can set the number of recursive layers, python3 defaults to 100 layers.

9.1 Recursive factorial##

Find the factorial of an integer, for example, if you give 5, the factorial is: 54321

# If you don&#39;t use a function, how should this factorial be written? It can be achieved simply with a for function.

multiplication =1
n =int(input('Please enter a number:'))for i inrange(1,n):
 multiplication  *= i
print(multiplication)

# What if we need to use a function to write it? But it is a non-recursive version.

def factorial(n):
 result = n
 for i inrange(1,n):
  result *= i
 return result
number =int(input('Please enter a positive integer:'))
result =factorial(number)print("%The factorial of d is:%d"%(number,result))

# The recursive version is as follows
def factoria2(m):if m ==1:return1else:return m *factoria2(m-1)

number2 =int(input('Please enter a positive integer:'))
result2 =factoria2(number2)print("%The factorial of d is:%d"%(number2,result2))

9.2 Fibonacci Sequence##

def  rabbit(n):if n ==1 or n ==2:
   rabbit_num =1else:
   rabbit_num =rabbit(n-1)+rabbit(n-2)return rabbit_num

print(rabbit(int(input("Please enter an integer:"))))

# The results are as follows:

Please enter an integer: 206765

9.3 Tower of Hanoi##

def hanoi(n,x,y,z):if n ==1:print(x,'-->',z)else:hanoi(n-1,x,z,y)  #Before n-1 plate moved from x to y
  print(x,'-->',z)  #Move the nth plate from x to z
  hanoi(n-1,y,x,z)  #N on y-1 plate moves to z

n =int(input('Please enter a number:'))hanoi(n,'X','Y','Z')

# The results are as follows:
Please enter a number: 4
X --> Y
X --> Z
Y --> Z
X --> Y
Z --> X
Z --> Y
X --> Y
X --> Z
Y --> Z
Y --> X
Z --> X
Y --> Z
X --> Y
X --> Z
Y --> Z

Recommended Posts

Functions in python
07. Python3 functions
Python functions
Learn Python in one minute | Python functions (on)
03. Operators in Python entry
Join function in Python
12. Network Programming in Python3
print statement in python
Concurrent requests in Python
Install python in Ubuntu
Context management in Python
Arithmetic operators in python
Write gui in python
MongoDB usage in Python
Str string in Python
Computational Geometry in Python
Concurrent requests in Python (part 2)
Subscripts of tuples in Python
Talking about inheritance in Python
Noteworthy update points in Python 3.9
Containerize Python applications in 3 minutes
What is introspection in python
python functions, classes, modules, packages
What is object-oriented in python
Generators and iterators in Python
Talking about strings in Python
The usage of wheel in python
Summary of logarithm method in Python
Use of Pandas in Python development
Use nohup command instructions in python
Is there function overloading in python
Getting started with Numpy in Python
Detailed sorting algorithm (implemented in Python)
How to wrap in python code
What does rc1 mean in python
Common errors and solutions in python
Use of numpy in Python development
What does def in python do
Python | Master Lambda functions, four don&#39;t!
How to omit parentheses in Python
Detailed usage of dictionary in Python
Usage of os package in python
Several common modes of Python functions
Learn about garbage collection in Python
How to write classes in python
How to filter numbers in python
​What are the numbers in Python?
How to read Excel in Python
There are several keywords in Python
Everything in Python is an object
How to view errors in python
What does np do in python
How to write return in python
Talking about the modules in Python
How to understand variables in Python
How to clear variables in python
Compare Excel, learn Python window functions
The usage of tuples in python
How to use SQLite in Python
Description of in parameterization in python mysql
Python multithreading