Getting started and using Python functions

     Functions are code blocks with names that are used to accomplish specific tasks. To perform a specific task defined by the function, you can call the function. When you need to perform the same task multiple times in the program,

You don't need to repeatedly write the code to complete the task, but just call the function that performs the task and let Python run the code.

1. Define the function

      (1) Defining a function has the following rules:

  • The function code block starts with the  def  keyword, followed by the function identifier name and parentheses  () .
  • Any incoming parameters and independent variables must be placed between parentheses, and the parentheses can be used to define parameters.
  • The first line of the function can optionally use a docstring—used to store the function description.
  • The content of the function starts with a colon: and is indented.
  • return [expression]  End the function and optionally return a value to the caller. Return without an expression is equivalent to returning None.

   

Here is a simple use case:

def greet_user():
    """显示简单的问候语"""
    print("Hello!")


greet_user()

  (2) Actual and formal parameters

     The following is a test case:

def sum_num(a, b):
    return a + b


print(sum_num(1, 2))

In the above program, the variables a and b are formal parameters, which are local variables defined in sum_num, 1 and 2 are actual parameters, and the actual parameters are the information passed to the function when the function is called.

When we call the function sum_num, 1 and 2 are passed, which is equivalent to executing a = 1, b = 2. At this time, the value stored in a is 1, and the value stored in b is 2.

2. Pass actual parameters

       Since the function definition may contain multiple formal parameters, the function call may also contain multiple actual parameters. There are many ways to pass actual parameters to a function, you can use positional parameters,

This requires that the order of the actual parameters is the same as the order of the formal parameters; keyword actual parameters can also be used, where each actual parameter is composed of variable names and values; lists and dictionaries can also be used.

    (1) Position actual parameters

              When calling a function, Python must associate each actual parameter in the function call with a formal parameter in the function definition. For this reason, the simplest way to associate is based on the order of the actual parameters. This type of association is called a positional argument.

def sum_num(a, b):
    print(a)
    print(b)
    return a + b


print(sum_num(1, 2))

       In the above code, when we are calling a function, we pass in 1 and 2, and the called function will directly assign 1 to a and 2 to b in the order of the parameters. If the incoming parameters are 2 and 1, in order, the value in a is 2 and the value in b is 1.

(2) Keyword arguments

        The keyword argument is the name-value pair passed to the function. The name and value are directly associated in the actual parameter, so there is no confusion when passing the actual parameter to the function.

The keyword argument saves you from having to consider the order of the arguments in the function call, and clearly indicates the purpose of each value in the function call.

def sum_num(a, b):
    print(a)
    print(b)
    return a + b


print(sum_num(a=1, b=2))

print(sum_num(b=2, a=1))

In the actual parameter, we directly set a = 1, b = 2. Regardless of the order, we have now associated the specific value with the formal parameter, so we can get the same result.

(3) Default value

        When writing a function, you can assign a default value to each formal parameter. When an actual parameter is provided to a formal parameter in the calling function, Python will use the specified actual parameter value; otherwise, it will use the default value of the formal parameter. therefore,

After assigning the default value to the formal parameter, the corresponding actual parameter can be omitted in the function call. Using default values ​​can simplify function calls and clearly indicate the typical usage of the function.

        Note that when using default values, the parameters without default values ​​must be listed first in the parameter list, and then the actual parameters with default values ​​must be listed. This allows Python to still correctly interpret the location arguments.

def sum_num(a, b=2):
    print(a)
    print(b)
    return a + b


print(sum_num(1))

In the above code, when we call the function, only 1 is passed in. At this time, 1 will automatically match 1 without the default value, and then b uses the default value 2.

 (4) Variable length parameters

     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 three types of parameters and will not be named when declared.

def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   print (vartuple)
 
# 调用printinfo 函数
printinfo( 70, 60, 50 )

If no parameters are specified when the function is called, it is an empty tuple. We can also not pass unnamed variables to the function. Examples are as follows:

def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   for var in vartuple:
      print (var)
   return
 
# 调用printinfo 函数
printinfo( 10 )
printinfo( 70, 60, 50 )

There is also a parameter with two asterisks **, the parameters with two asterisks ** will be imported in the form of a dictionary.

def printinfo( arg1, **vardict ):
   "打印任何传入的参数"
   print ("输出: ")
   print (arg1)
   print (vardict)
 
# 调用printinfo 函数
printinfo(1, a=2,b=3)

   (5) Transfer mutable and immutable objects

           In python, types belong to objects, and variables have no types:

a=[1,2,3]

a="Runoob"

In the above code, [1,2,3]  is of type List, "Runoob"  is of type String, and variable a is of no type. It is just a reference to an object (a pointer), which can point to an object of type List, or It points to 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.

  • Immutable type: After the variable is assigned  a=5,  then a=10 is assigned  . Here, an int value object 10 is actually generated, and a is made to point to it, and 5 is discarded, not changing the value of a, which is equivalent to newly generating a .

  • Variable type: variable assignment  la=[1,2,3,4]  and then assignment  la[2]=5  is to change the value of the third element of list la, la itself is not changed, just a part of its internal value Has been modified.

Python function parameter passing:

  • Immutable types: C++-like value transfer, such as integers, strings, tuples. For example, fun(a), only the value of a is passed, and the a object itself is not affected. If the value of a is modified inside fun(a)), a new a is generated.

  • Variable types: C++-like passing by reference, such as lists and dictionaries. For example, fun(la), it will actually pass la, and the la outside the fun will also be affected after modification

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

3. Return value

    A function does not always display the output directly. Instead, it can process some data and return a value or set of values. The value returned by the function is called the return value. In a function, you can use the return statement to return the value to the line of code that called the function.

The return value allows you to move most of the heavy work of the program to the function to complete, thereby simplifying the main program.

(1) Return a simple value

       

def sum_num(a, b):
    return a + b


print(sum_num(1, 2))

(2) Return to dictionary and list

         Functions can return any type of value, including more complex data structures such as lists and dictionaries

def sum_num(a, b):
    ls = [a, b]
    return ls


print(sum_num(1, 2))

4. Anonymous function

      Python uses lambda to create anonymous functions.

      The so-called anonymous means that a function is no longer defined in a standard form such as the 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.
  • The lambda function has its own namespace and cannot access parameters outside of its parameter list or in the global namespace.
  • Although the lambda function can only write one line, it is not equivalent to the C or C++ inline function. The purpose of the latter is to not occupy the stack memory when calling a small function, thereby increasing the operating efficiency.
sum = lambda arg1, arg2: arg1 + arg2
 
# 调用sum函数
print ("相加后的值为 : ", sum( 10, 20 ))
print ("相加后的值为 : ", sum( 20, 20 ))

 

Guess you like

Origin blog.csdn.net/Light20000309/article/details/112901447