Python introduction notes 8 (functions)

Functions are organized, reusable snippets of code used to implement a single, or associated function. Function can improve the modularity of application and the reuse rate of code, which is more convenient for the program to realize complex functions

1, Define a function

Functions in Python are divided into built-in functions and custom functions. Built in functions are built in Python and can be used directly, such as print() function and input() function. User defined functions are called user-defined functions. Next, we will introduce the creation of user-defined functions.

1. The function code block starts with the keyword "def", followed by the function identifier name and parentheses ().

2. Any incoming parameters and arguments must be placed in the middle of parentheses, which can be used to define parameters.

3. The first line of the function can optionally use the document string - used to store the function description.

4. The function content starts with colon and is indented.

5. Return [expression] ends the function and selectively returns a value to the caller. A return without an expression is equivalent to returning None.

def Function name (parameter list):
    Function body

2, Function call

The calling function can directly reference the function name and add parameters. The following example calls the {printme() function:

# Define function
def printme( str ):
   # Print any incoming strings
   print (str)
   return
 
# Call function
printme("I want to call a user-defined function!")

3, Parameter transfer

The parameter list consists of a series of parameters separated by commas. When calling a function, if you need to pass parameters to the function, the parameters passed in are called arguments, and the parameters at the time of function definition are called formal parameters. Data can be passed between arguments and formal parameters.

Mutable and immutable objects

Immutable type: the variable is assigned a value of a=5, and then assigned a value of a=10. In fact, an int value object 10 is newly generated, and then a points to it, while 5 is discarded. Instead of changing the value of a, it is equivalent to newly generating a.

Variable type: if the variable is assigned la=[1,2,3,4] and then assigned la[2]=5, the value of the third element of list la is changed. la itself does not move, but some of its internal values are modified.

1. Transfer immutable object instances

def change(a):
    print(id(a))   # It points to the same object
    a=10
    print(id(a))   # A new object
 
a=1
print(id(a))
change(a)

4379369136
4379369136
4379369424

It can be seen that before and after calling the function, the formal parameter and the actual parameter point to the same object (the object id is the same). After modifying the formal parameter inside the function, the formal parameter points to a different id.

2. Transfer variable object instance

If the variable object modifies the parameters in the function, the original parameters are also changed in the function calling the function. For example:

# Description of writable function
def changeme( mylist ):
   "Modify 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 function: ", mylist)

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

The passed in function uses the same reference as the object that adds new content at the end.

4, Parameters

The following are the formal parameter types that can be used when calling the function: required parameter, keyword parameter, default parameter and variable length parameter

1. Required parameters

Required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.

#Description of writable function
def printme( str ):
   "Print any incoming strings"
   print (str)
   return
 
# Calling the printme function without parameters will report an error
printme()    

2. Keyword parameters

Function calls use keyword parameters to determine the passed in parameter values. Using keyword parameters allows the order of parameters in function calls to be inconsistent with that in declarations, because the Python interpreter can match parameter values with parameter names.

#Description of writable function
def printme( str ):
   "Print any incoming strings"
   print (str)
   return
 
#Call the printme function
printme( str = "Python yyds")

Python yyds

3. Default parameters

When a function is called, if no parameters are passed, the default parameters are used. In the following examples, if no age parameter is passed in, the default value is used:

#Description of writable function
def printinfo( name, age = 35 ):
   "Print any incoming strings"
   print ("name: ", name)
   print ("Age: ", age)
   return
 
#Call the printinfo function
printinfo( age=50, name="runoob" )
print ("------------------------")
printinfo( name="runoob" )

Will output the name:  runoob  Age:  50

4. Variable length parameters

When a function has to handle more parameters than it originally declared. These parameters are called variable length parameters. Unlike the above two parameters, they are not named when declared. The basic syntax is as follows:

# Description of writable function
def printinfo( arg1, *vartuple ):
   "Print any incoming parameters"
   print ("output: ")
   print (arg1)
   print (vartuple)
 
# Call the printinfo function
printinfo( 70, 60, 50 )

70
(60, 50)

5, Anonymous function

python uses lambda to create anonymous functions. Anonymity means that a function is no longer defined in the standard form of def statement. Lambda is just an expression, and the function body is much simpler than def. The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions. Lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace.

sum = lambda arg1, arg2: arg1 + arg2
 
# Call 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

6, return statement

The return [expression] statement is used to exit the function, and also to output data from the inside of the function to the outside of the function. Optionally returns an expression to the caller. Return statements without parameter values return None.

# Description of writable function
def sum( arg1, arg2 ):
   # Returns the sum of 2 parameters "
   total = arg1 + arg2
   print ("Within function : ", total)
   return total
 
# Call sum function
total = sum( 10, 20 )
print ("Out of function : ", total)

Within function :  30
 Out of function :  30

7, Scope of variable

The code range in which a variable works is called the scope of the variable, which is closely related to the location of the variable definition. According to different scopes, variables can be divided into local variables and global variables.

Local variables: ordinary variables defined inside the function only work inside the function. When the function is executed, the local variables are automatically deleted and can no longer be used.

Global variable: if you need to assign a value to a variable defined outside the function inside the function, the scope of the variable cannot be local, but should be global. Variables that can act both inside and outside the function are called global variables. If you want to declare a global variable inside the function, you can declare it through the global keyword.

x=3    #global variable

def fun():
    x = 3      #local variable
    global b   #Declare a variable as a global variable through global. If there is a global variable with the same name, it has the same meaning

        

Keywords: Python Embedded system

Added by skippa on Wed, 15 Dec 2021 11:26:55 +0200