07. Python3 functions

Python3 function

Functions are organized, reusable, code segments used to implement a single or related function.
Functions can improve application modularity and code reuse. Python provides many built-in functions, such as print(). We can call it directly. To call a function, we need to know the name and parameters of the function. You can view the documentation directly from the official Python website:
https://docs.python.org/3/library/functions.html

You can also view the help information of the print function in the interactive command through help (print)

But you can also create a function yourself, which is called a user-defined function.

Define function

# 1. The function code block starts with the def keyword, followed by the function identifier name and parentheses()  
# 2. Any incoming parameters and custom variables must be placed in the middle of the parentheses, between the parentheses can be used to define parameters.  
# 3. The first line of the function can optionally use the document string to store the function description
# 4. The function content starts with a colon and is indented.
# 5. reture[expression]结束函数,选择性地返回一个值调用方,不带expression的return相当于返回None.  

# function:By function(Accomplish one thing)Oriented,log in,registered,len,一个function就是一个功能
# Use as you tune
# 
# Function
# 1. Reduce code duplication.
# 2. Make the code more readable.

**Syntax: **Python defines functions using the def keyword, the general format is as follows:

def function name(parameter list):  
Function body

# By default, parameter values and parameter names are matched in the order defined in the function declaration.  

# The def keyword starts with the function name and parentheses after a space(),Finally there is one":"
# def is fixed and cannot be changed,That is, the keyword that defines the function
# Function name: Function name只能包含字符串、下划线和数字且不能以数字开头。虽然Function name可以随便起,但我们给函数起名字还是要尽量简短,并且要具有可描述性

Example1****We use function to output "Hello World!"

def hello():print('hello world')hello() 

# hello world

More complicated applications, with parameter variables in the function

# Find the number of elements,length,Traditional method low
li1 =[1,2,3,4,5]
count =0for i in li1:
 count +=1print(count)

# The function realizes how many elements in the list
def my_len(l):
 count =0for i in l:
  count +=1print(count)my_len(li1)

def area(width, height):return width * height  
  
def print_welcom(name):print("Welcome",name)print_welcom("You-Men")  
w =4  
h =5print("width = ",w,"height = ",h,"area =",area(w,h))

Function call

Example2

Define a function: Give the function a name, specify the parameters contained in the function and the structure of the code block.
After the basic structure of this function is completed, you can execute it through another function call or directly from the Python command prompt.
The following example calls the printme() function.

# When the function encounters the function name+(), The function will be executed

def printme(str):print(str)returnprintme("I want to call a custom function")

The return value of the function

A function is to encapsulate a function. This function usually has a final result. For example, if you write a login function, does the final login succeed or not need to return you a result? And have we all used the len function? It gets the total number of elements of an object, and it will definitely return a result like the number of elements in the end:

So how to set this return value? This requires a keyword in python: return

def date():print("Take out the phone")print("Open Momo")print('Swipe left')print('Swipe right')print("Find a beautiful girl")returnprint("ask her,No appointment!")print("ok go up")
  

# to sum up
# 1. When return is encountered in the function, the function ends and the execution will not continue

# 2. return will return the value for the execution of the function
	#If nothing is written after return, or there is no return in the function, the result returned is None
 # If a value is written after return, return this value to the caller
	#If multiple values are returned, it is a tuple(Tuple)Returned in the form of,调用者可以直接使用Tuple的

Function parameter passing####

The above talks about function structure, function execution, function return value, and a preliminary understanding of the function, and then the function parameters.
Functions are function-oriented. The codes in the functions we wrote above are all hard-coded, that is to say, the changes in the function are very troublesome, so this kind of hard-coded code can be solved by passing parameters.

In Python, the type belongs to the object, and the variable has no type

a=[1,2,3]  
a="YouMen"

In the above code, [1,2,3] is of type List, "Runoob" is of type String, and variable a has no type, it is just a reference to an object (a pointer), so It can point to an object of type List or an object of type String.

Mutable and immutable objects

In python, strings, tuples, and numbers are unchangeable objects, while lists, dicts, etc. are objects that can be modified.

Python function parameter passing

Immutable type: C++-like value transfer, such as integers, strings, tuples, such as fun(a), only the value of a is passed, and the a object itself is not affected. For example, fun(a) internally modifies the value of a, but Modifying another assigned object will not affect a itself.

Variable type: Pass by reference similar to C++, such as list, dictionary. For example, fun(la), it actually passes la, and the modified la outside the fun will also be affected.

Everything in Python is an object. Strictly speaking, we can't say value passing or reference passing, we should say immutable objects and passing mutable objects

Python pass immutable object instance

def ChangeInt(a):  
 a =10  
	b =2ChangeInt(b)print(b)  

# The result of the above example is:  

# There is an int object 2 in the example, and the variable pointing to it is b,When passing the ChangeInt function, the variable b is copied by value. Both a and b point to the same Int object, in a=At 10 o'clock, a new int value object 10 is generated, and a point to him

**Pass the variable object instance **** The variable object changes the parameters in the function, then the original parameters are also changed in the function that calls this function, such as **

# Writable function description

def changeme( mylist ):"Modify the incoming list"  
 mylist.append([1,2,3,4])print("Value in function: ", mylist)return  
    

# Call the changeme function

mylist =[10,20,30]changeme( mylist )print("Value outside the function: ", mylist)  

# The incoming function and the object with new content added at the end are the same reference, so the output result is as follows:  

Value in function:[10,20,30,[1,2,3,4]]  
Value outside the function:[10,20,30,[1,2,3,4]]

parameter####

The following are the formal parameter types that can be used to call a function:

Required parameters

The parameters must be passed into the function in the correct order, and the number of parameters must be the same as that of the declaration
To call the printme() function, you must pass in a parameter, otherwise there will be a syntax error

# Writable function description

def printme(str):"Print any incoming string"print(str)
 # return

# No parameter will be reported
printme('Hello')
Keyword parameters

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

The use of keyword parameters allows the order of function calls to be different from that of declarations, because the Python interpreter can match parameter values with parameter names

The following example uses the parameter name when calling the function printme()

# Write a function that only accepts two numbers,int parameter, the function function will return a larger number

def sum(a,b):if a > b:return a
 elif a == b:return"equal"else:return b

print(sum(2,2))

# Actual angle
# 1. Location parameter,In order, one-to-one correspondence
# 2. Keyword parameter,One to one correspondence
# 3. Mixed parameters,The positional parameter must be before the keyword parameter

The following example demonstrates that the use of function parameters does not require a specified order

def printfo(name,age):print("first name",name)print("age",age)returnprintfo(age=10,name='youmen')

# Name youmen
# Age 10
Default parameters

When calling the function, if no parameters are passed, the default parameters will be used. If the age parameter is not passed in the following example, the default value will be used

# The meaning of the setting lies in the commonly used
# Writable function description

def printfo(name,age=15):"Print any incoming string"print("first name",name)print("age",age)returnprintfo(age=50,name='YouMen')print("--------------")printfo(name='Flying')

# Name YouMen
# Age 50--------------
# Name Flying
# Age 15
Variable length parameter

You may need a function that can handle more parameters than it was originally declared. These parameters are called indefinite-length parameters, which are different from the above two types of parameters and will not be named when declared. The basic syntax is as follows:

# Writable function description
def printfo(arg1,*vartuple):"Print any incoming parameters"print("Output:")print(arg1)print(vartuple)  
  
# Call printfo function
printfo(30,40,50,60)  
  
# Output:  
# 30  
# (40,50,60)

**There is also a parameter with two asterisks The basic syntax is as follows:

# Writable function description
def printfo(arg1,**vardict):print("Output:")print(arg1)print(vardict)printfo(1234,a=2,b=3)
  
# Added two asterisks**Will be imported as a dictionary
# Output:  
# 1234  
# {' a':2,'b':3}

If it is a parameter after * alone, it must be passed in with a keyword:

# Writable function description
def printfo(a,b,*,c):print("Output:")print(a)print(b)print(c)printfo(1,2,c=3)

# If it is printfo(1,2,3)Will report an error
  
# Output:  
# 1  
# 2  
# 3
Universal parameters#####

( args)*

# Universal parameters
# * args,Conventional name,
# * Function definition,*Representative aggregation,He aggregates all the positional parameters into a primitive ancestor and assigns it to args

# Write a function:Calculate the sum of all the numbers you pass into the function
def func(*args):
 count =0for i in args:
  count += i
 return count

print(func(1,2,3,4,5,6,7))

*(*kwargs)

# **kwargs
# Function definition,**Aggregate all keyword parameters into a dictionary,Assigned this dictionary to kwargs
def func(**kwargs):print(kwargs)func(name='youmen',age=18,sex='boy')

# {' name':'youmen','age':18,'sex':'boy'}

def func(a,b,*args,sex='male',c,**kwargs):print(a,b)print(sex)print(args)print(c)print(kwargs)func(1,2,3,4,5,6,sex='Female',c=60)

# 12
# Female
# (3,4,5,6)
# 60
# {}

Anonymous function

Python uses lambda to create anonymous functions. The so-called anonymous means that you no longer use the standard form of def statement to define a function.

grammar

# The syntax of lambda function contains only one statement, as follows:  
lambda [arg1 [,arg2,....argn]]:expression  
# The following example:  
  
# Writable function description
sum = lambda arg1,arg2 : arg1 + arg2  
  
# Call the sum function
print("The added value is:",sum(10,20))print("The added value is:",sum(20,20))  
  
The added value is:30  
The added value is:40

return statement

The return [expression] statement is used to exit a function and optionally return an expression to the caller. The return statement without parameter values returns None. The previous examples did not demonstrate how to return a value. The following example demonstrates the use of the return statement:

# Writable function description
def sum(arg1,arg2):"Returns the sum of 2 parameters"  
 total = arg1 + arg2  
 print("Inside function:",total)return total  
  
# Call the sum function
total =sum(10,20)print("Outside the function:",total)  
  
Inside function:30  
Outside the function:30

Mandatory positional parameters

def f(a, b,/, c, d,*, e, f):print(a, b, c, d, e, f)  
  
# The following method of use is correct:f(10,20,30, d=40, e=50, f=60)  
  
The following methods will cause errors:f(10, b=20, c=30, d=40, e=50, f=60)  #b can not use the form of keyword parameters
f(10,20,30,40,50, f=60)  #e must use the form of keyword parameters

Function namespace, scope####

After the python interpreter starts to execute, it will open up a space in memory. Whenever a variable is encountered, the relationship between the variable name and the value is recorded, but when it encounters a function definition, the interpreter just Reading the function name into the memory indicates that the function exists. As for the variables and logic inside the function, the interpreter does not care. That is to say, the function is just loaded in at the beginning, and nothing more, only when the function is called and When accessing, the interpreter will open up the internal space of the variables according to the variables declared inside the function. As the function is executed, the space occupied by the internal variables of the function will also be cleared as the function is executed.
Let us first recall how the Python code is run when it encounters a function. After the Python interpreter starts to execute, a space is opened in memory. Whenever a variable is encountered, the variable name and value are separated The corresponding relationship is recorded, but when it encounters a function definition, the interpreter only symbolically reads the function name as memory, indicating that it knows that the function exists. As for the variables and logic inside the function, the interpreter does not care at all.
When the function is called, the Python interpreter will open up a piece of memory to store the contents of the function. At this time, we will pay attention to which variables are in the function, and the variables in the function will be stored in the newly opened memory. The variables in the function can only be used inside the function, and as the function is executed, all the contents of this memory will be cleared.
We gave this "store the relationship between name and value" a name-the namespace.
At the beginning of code execution, the space created to store the "relationship between variable name and value" is called the global namespace;

The temporary space opened up during the operation of the function is called the local namespace or the temporary namespace

In the py file, a space that stores the relationship between variables and values is called the global namespace, and when a function is executed, a space is temporarily opened in the memory to temporarily store the relationship between variables and values in the function, this is called a temporary namespace, Or local namespace.

There is also a space in python called the built-in namespace: the built-in namespace stores some special variables such as built-in functions that are ready to use: input, print, list, etc.

# 1. Global namespace--->We directly in the py file, the variables declared outside the function belong to the global namespace

# 2. Local namespace--->Variables declared in the function will be stored in the local namespace

# 3. Built-in namespace--->Store the name provided by the python interpreter,list,tuple,str,int these are built-in namespaces.
Loading order

The so-called loading order is the order in which these three spaces are loaded into memory, that is, the order in which these three spaces are created in memory. Do you think they can be created at the same time? Definitely not, so who will come first? Let's make a quick look: after starting the python interpreter, even if no variables or functions are created, there will still be some functions that can be used directly, such as abs(-1), max(1,3), etc., when starting the Python interpretation It’s already imported into the memory for us to use, so it must first load the built-in namespace, and then start executing from the top of the file to the next line. At this time, if an initialization variable is encountered, a global namespace will be created. , Store these correspondences in, and then temporarily open up a space in the memory when the function is executed, load some variables in the function, and so on. So the loading sequence of these three spaces is: built-in namespace (load at the beginning of program operation) -> global namespace (program running: load from top to bottom) -> local namespace (program running: load only when called.

Value order

The order of value is to refer to a variable. From which space to start the reference, there is a key point: Starting from that space to refer to this variable, we will give examples:

# If you refer to a variable in the global namespace, first refer to the local namespace, the global name, if not, then refer to the built-in namespace

# sum=666print(sum)

def func():
 # sum =555print(sum)func()

name='flying'
def func():
 # name='youmen'print(name)func()

# Value order(The principle of proximity)
# From(Local variable lookup)Local namespace--->Global namespace--->Built-in name space
Scope#####

The scope is also the scope of scope, control the effective scope to see the global scope and the local scope

Global scope: Contains built-in namespace and global namespace, which can be used anywhere in the entire file (follow the execution line by line from top to bottom)

Local scope: can be used inside a function

Scope namespace

# 1. Global scope:Global namespace+Built-in namespace
# 2. Local scope:Local namespace

def func1():print('in fun1')print(3)

def fun2():print('in fun2')print(4)func1()print(1)fun2()print(2)

# in fun1
# 3
# 1
# in fun2
# 4
# 2 print("#############################")
def fun2():print(2)
 def func3():print(6)print(4)func3()print(8)print(8)fun2()

Function name####

func()
# 1. The function name points to the memory address of the function.
# Function name+()Can execute the function

# 2. Function name is a variable,Since it is a variable, it can be assigned

# 3. Function name can be used as element of container data type
def fun1():print("in fun1")

def fun2():print("in fun2")

def fun3():print("in fun3")

li1 =[fun1,fun2,fun3]for i in li1:i()

# 4. Function name can be used as function parameter

def func():print('in func')

def func1(x):  # x = func
 print('in func1')return x

ret =func1(func)ret()
Keywords (Global)
# When our program encounters the need of local scope to change some variables of the global scope, we can use the keyword global:
# global first function:Variables in the global scope can be changed in the local scope.

a =1
def func():print(a)func()
# a =1
def func():
 global a
 a +=1print(a)func()

Recommended Posts

07. Python3 functions
Python functions
python functions, classes, modules, packages
Python multithreading
Python FAQ
Python3 dictionary
Python3 module
python (you-get)
Python string
Python basics
Python descriptor
Python basics 2
Python exec
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python toolchain
Python multitasking-coroutine
Python overview
python introduction
Python | Master Lambda functions, four don't!
Python analytic
Several common modes of Python functions
Python basics
Python basics 3
Python multitasking-threads
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
python queue Queue
Compare Excel, learn Python window functions
Python basics 4
Python basics 5
Getting started with python-2: functions and dictionaries
Learn Python in one minute | Python functions (on)
Python answers questions
Python basic syntax (1)
Python exit loop
Ubuntu16 upgrade Python3
ubuntu18.04 install python2
Python classic algorithm
Relearn ubuntu --python3
Python2.7 [Installation Tutorial]
Python string manipulation
Python 3.9 is here!
Python study notes (1)
python learning route
CentOS7 upgrade python3
Python3 basic syntax
Python review one
linux+ubuntu solve python
Python learning-variable types
7 features of Python3.9
Python file operation
Python design patterns
Python - centos6 installation