Home > Backend Development > Python Tutorial > Function basics (python)

Function basics (python)

不言
Release: 2018-04-04 15:54:05
Original
1407 people have browsed it

The content of this article is the basic knowledge of Python functions. Now I share it with you. Friends in need can refer to the content in the article

Function: If you need a certain piece of code multiple times when developing a program, but in order to improve writing efficiency and code reuse, code blocks with independent functions are organized into a small module
This is the function

Function definition and call

<1>Define function
The format of defining a function is as follows:

def function name():
Code
< 2>Call the function

After defining the function, it is equivalent to having a code with certain functions. If you want these codes to be executed, you need to call it

Calling the function is very simple , the call can be completed through the function name ()


Function parameters (1)

In order to make a function more general, that is, if you want it to calculate the sum of two numbers, just Let it calculate the sum of two numbers. When defining the function, you can let the function receive data.
This solves this problem. This is the parameter of the function

<1> Define with parameters Function

Examples are as follows:

def add2num(a, b):
c = a+b
print c

<2> Call with parameters Function

Take calling the add2num(a, b) function above as an example:


def add2num(a, b):
c = a+b
print c

Add2num(11, 22) #When calling a function with parameters, you need to pass the data in parentheses
<4> Summary

Parameters in parentheses when defining , used to receive parameters, are called "formal parameters"

The parameters in parentheses when calling are used to pass to the function, called "actual parameters"

Function return Value (1)

<1>Introduction to "return value"

The so-called "return value" is the final result given to the caller after the function in the program completes one thing

<2>Function with return value

If you want to return the result to the caller in the function, you need to use return

in the function. The following example:

           def add2num(a, b):
               c = a+b
                                                 
# <3>Save the return value of the function

In the example of "buying cigarettes" mentioned at the beginning of this section, when your son gives you the cigarette at the end, you must be from your son Take it over in your hand, right? The same is true for programs. If a function returns a data, and you want to use this data, you need to save it

An example of the return value of the saved function is as follows:

# Define function
def add2num(a, b):
return a+b

#Call the function and save the return value of the function
result = add2num(100,98)

     #Because result has saved the return value of add2num, so it can be used next
                                                                                                                                     

Function return value (2)
Can we return multiple values ​​in python?

>>> def pid(a, b):
... shang = a//b
... yushu = a%b
... return shang . yu
1

The essence is to use the tuple



4 types of functions

The function depends on whether there are parameters and whether there is a return value , can be combined with each other, there are 4 types in total

No parameters, no return value
                                            ’ ’ ’ s ’ s 1 ‐ ‐ ‐ t t to t t                                       t t                                             ’ ’ s ’ s ’ s ’ s ’ s ’

This type of function cannot accept parameters and has no return value. Generally, to print functions similar to the prompt light, use this type of function

<2>No parameters, return value Value function

                                                                                                                                                                                                                        ,   , , , , ,                   herself - herself herself herself she herself she She Shen Shen Shen Shen Shen her out her out there heron to do herself in. #DEF GETTEMPERATURE ():

#Here is some of the processing process of getting the temperature

#In order to simulate the return of a data
RETURN 24
## TEMPERAN = = getTemperature ()
PRINT ('The current temperature is:%d'%temporarative)

Result:
## This current temperature is: 24

& lt; Functions with parameters and no return value

This type of function can receive parameters, but cannot return data. Generally, this type of function is used when setting data for certain variables without requiring a result

# & lt; 4 & gt; there are parameters, and there are functions with returning value

This kind of functions, which can not only receive parameters, but also return a certain data. Generally, it is like data processing and applications that require results. , use this kind of function


        # Calculate the cumulative sum of 1~num
          def calculateNum(num):

                                          ‐                               to calculate the cumulative sum of 1~num i & lt; = num:

Result = result + i

i + = 1
## Regent result

ain = Calculatenum (100) #A 'The cumulative sum of 1~100 is: %d'%result)

      Result:

          The cumulative sum of 1 to 100 is: 5050

                                ’ s ’ s ’ ’ s t . ##                                                                                                                                                                      The following example will print the default AGE. name
PRINT "Age", Age

#n n n
Printinfo (name = "miki")
Printinfo (Age = 9, name = "miki")

                                                                                                                                                                                                                    The output result of the above example:

                                               Name: Miki
Age 9

Note: Parameters with the default value must be at the end of the parameter list.

                                                                                                                                                                     t;", line 1
Syntaxerror: NON-Default Argument Follows Default ARGUMENT
# 2. Performance parameters

Sometimes it may need a function to process more parameters than when the original statement. These parameters are called variable-length parameters and are not named when declared.

The basic syntax is as follows:
##        function_suite
                         return [ Expression]

Added a variable (*) variable ARGS will store all the unnamed variable parameters, ARGS is the meta -group; and the variable KWARGS plus ** will store the naming parameters,
is shape as shaped like it key=value parameters, kwargs is a dictionary.

             > print "a =", a
                                                                                                                                                                                    . for key , value in kwargs.items():
                                                                                                                                                                                                                                                          ​ m = 6, n = 7, p = 8)#注意 m m m m m m
A = 1
B = 2
ARGS = (3, 4, 5)
Kwargs:
p = 8
                                                                                                                                                ; c = (3, 4, 5)
                                                                                                     >>> fun(1, 2, *c, **d) # Pay attention to the parameter passing method of tuples and dictionaries
, 5)
                                                                                                                   ;> ;>
                                                                                    args = ( (3, 4, 5), {'p': 8, 'm': 6, 'n': 7})
                                                                                                                   

3. Quote Chuanyin

The variables of the variable type and unchanged types are used as function parameters, respectively?
Does Python have pointer parameter passing similar to that in C language?

                                                                                                                  ## >>> a_int = 1
;                                      1
                                                                                                                   >> selfAdd(a_list)
>>> a_list
                                                                                                                                                                                                                                                                                       ​For immutable types, the dependent variable cannot be modified, so the operation will not affect the variable itself
           ; for variable types, the operation in the function body may change the passed parameter variable.


Nested calls of functions

def testB():
print('---- testB start----')
print('Here It is the code executed by the testB function --- testA start----')

testB()

                                                                                                                                          testA()                                              ​- testA start----
---- testB start----
---- Here is the code for testB function execution
---- testB end----
---- testA end----


## Thinking & Implementation 1

Write a function to print a horizontal line
Print a custom number of horizontal lines

                                                                                                                                                                                                          # Print a horizontal line
def printNumLine(num):
i=0

Because the printOneLine function has completed the function of printing horizontal lines,
only needs to call this function multiple times
While I & lt; num:
Printoneline ()
I+= 1

PRINTNUMLINE (3)
## thinking & Implementation 2
##的和
            写一个函数求三个数的平均值

        参考代码2


        # 求3个数的和
        def sum3Number(a,b, c):
            return a+b+c # return 的后面可以是数值,也可是一个表达式

        # 完成对3个数求平均值
        def average3Number(a,b, c):

            # Because the sum3Number function has already completed the sum of 3 numbers, so it only needs to be called
            # That is, the 3 received numbers can be passed as actual parameters
        sumResult = sum3Number(a,b,c)
        aveResult = sumResult/3.0
                              average3Number( ) , you can define local variables with the same name, but using each one will not affect
The role of local variables, in order to temporarily save data, you need to define variables in the function for storage, this is its role

Global variables
If a variable can be used in a function or in other functions, such a variable is a global variable

The demo is as follows:

# Define global variables
a = 100

def test1():
print(a)

def test2():
print(a)

       # Calling functions
          test1()
          test2()

                                                                                                                                                                                                                                                         # If you modify a global variable in a function, you need to use global to declare it, otherwise an error will occur.
If the name of the global variable is the same as the name of the local variable, then the local variable is used. A little trick to make the powerful dragon not overpower the local snake


recursive function
If a function does not call other functions internally, but itself, this function is a recursive function.
For example, let’s calculate the factorial n! = 1 * 2 * 3 * ... * n
def calNum(num):
i = 1
return = 1

while i<=num:
while i<=num:
return *= i
i+=1

return result

ret = calNum(3)
print(ret)


Anonymous function

Use the lambda keyword to create a small anonymous function. This type of function gets its name from the fact that the standard step of declaring a function with def is omitted.

The syntax of the lambda function only contains one statement, as follows:

lambda [arg1 [,arg2,...argn]]:expression

The following example:

sum = lambda arg1, arg2: arg1 + arg2

#Call sum function
print "Value of total: ", sum(10, 20)
print "Value of total : ", sum(20, 20)

The output result of the above example:

Value of total: 30
Value of total: 40

The Lambda function can receive any number of parameters but can only return the value of an expression

Anonymous functions cannot call print directly because lambda requires an expression
Application scenarios
Functions are passed as parameters

Self Define function

                                                                                                                                 , , ,                                                                          , , ,                                                   #                                                                                                            = 1
                                                                      using   using use with using ’         through through ’ through ’ using ’s ’ using ’s ’ using ‐ ‐ ‐ ‐ ‐ to be sorted by age or name?

stus = [
                                                                                                                                                                                                                                                                        {"name":"wangwu", "age":17}
]

Sort by name:

>>> stus.sort(key = lambda x: x['name'])
>>> stus
[{'age': 19, 'name': 'lisi'}, {'age': 17, 'name': 'wangwu '}, {'age': 18, 'name': 'zhangsan'}]

Sort by age:

>>> stus.sort(key = lambda x: x['age'])
>>> stus
[{'age': 17, 'name': 'wangwu'}, {'age': 18, 'name': 'zhangsan '}, {'age': 19, 'name': 'lisi'}]

Notes on using functions

1. Custom function

 <1> No parameters, no return value

def function name():
Statement


statement
Return The value that needs to be returned

Note:

Is there any back function? It depends on whether there is Return, because only Return can return data

In development, functions are often designed according to needs whether they need to return a value.
In a function, there can be multiple return statements, but as long as one return statement is executed, it means that the call of this function is completed

<3>With parameters and no return value

                                                                                                                                                                                                                                                                       because Pass some data together, and the called function needs to use parameters to receive it
                                                                                   
Value

# DEF Function Title (List of Shape Peris):
Sentence
RETURN The value you need to return

# & LT; The call function

& lt; 1 & gt;

If the call function is tangible when defined, then the parameters should be passed when calling

# & lt; 3 & gt; Consistent with the requirements in ;1>Variables defined in a function can only be used in this function (local variables)

<2>Variables defined outside the function can be used in all functions (global variables)
Related recommendations:


Introduction to Python basic functions

The above is the detailed content of Function basics (python). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template