Python Basics: Python functions

Source: Internet
Author: User

The function is the most used object in Python.

Simple Rules for function definitions:

1, defined with Def, followed by the function name and parameters and colon, format:

2, the function internal code block needs to indent

3, return the function value with return, the default return value is None

Format:

def function name (parameter):

code block

Return #可有可无 can also be used anywhere in the code block


Second, the use of return in the function:

Return can be used anywhere in the function, jumping directly out of the current function, ignoring other blocks of code.

# return can also be returned without parameters, returning the None

# you can have no return, and none of them return.

# return can also return a dictionary, list, function (the adorner is the function code block returned).


1, can jump out of if,while,for and other statements

Def use_return (): i = 0 while true:i + = 1 for j in Range (i): Print (J, end= ") If j = = 5:return J print () Use_return () # Run Result: I equals 5 will end Function "" "001012012301234 012345 "" "

The above function changes the calling method:

Print (Use_return ()) # The last line 0123455, and the last 5 is the value of the return function, which is the value of J. Try to break the last 5 line.

2. Call Function:

Functions are called using function names and parentheses. The function body is called without parentheses, which is equivalent to an individual name.

#  uses the above example #  call 1if use_return ()  == 5:    print (5) #  call 2for  i in range (0,use_return ()):                     print (i) #不能使用, because Use_return () returns a number, but not an int, it must first be assigned to a variable. Then call the variable V = use_return () for i in range (0,v):                     print (i)      #  call 3s = use_return () print (s) #  call function Body Func = use_returnprint (func)                           #  printed is the memory address of the Use_return function func ()                                #  Running Use_return function 

Third, the relationship between the function variables and the external variables:

1. Can change (mutable) and non-change (immutable) objects

strings, tuples, and numbers are immutable objects, while list,dict and so on are objects that can be modified.

2. Immutable Type:

# variable Assignment a=5 after the assignment of a=10, not the value of a changed, the variable is equivalent to a pointer, but the pointer is changed, 5 itself does not change, the point of 10 is a new address, instead of 5 into 10.

# Immutable types are passed into the function, and after the function is modified, the external variable values are not affected.

3. Variable type:

# variable Assignment la=[1,2,3,4] and then assign value la[2]=5, although the memory address that La points to does not change, but the internal value has changed, so it is mutable.

# a mutable type is inside the function of La itself, so modify la[2 within the function], and also change the la[2 outside the function]

def MODIFY_LA2 (La_value): la_value[2] = 99999la = [0, 1, 2, 3, 4, 5]MODIFY_LA2 (LA) print (' La =%s '% LA) # run result la = [0, 1 , 99999, 3, 4, 5]

4. Function variables look for the outermost layer

Def MODIFY_LA2 (): la[2] = 99999la = [0, 1, 2, 3, 4, 5]MODIFY_LA2 () print (' La =%s '% la) #modify_la2找不到la, the La,la outside the function must be written In front of the MODIFY_LA2 () call


Five, the function of the parameter transfer form:

1. Required parameters: When calling a function, write the corresponding value in the order of the variables

2. Keyword parameter: When calling a function, use variable name to assign value, variable = value

3. Default parameters: Parameter with value when defining function, Def user (name, age=20):, age=20 is the default parameter

4, indefinite length parameter:

# (*ARGS) variable length parameter, can only receive the necessary parameters, convert the parameters to list storage

# (**KWARGS) variable length parameter, can only receive the keyword parameters, and convert the parameters to dictionary storage

5. The order in which the parameters exist:

Required parameters, default parameters, *args, **kwargs

def MODIFY_LA2 (name, age=20, *args, **kwargs):

#age默认参数不起作用, the value must be assigned.

def MODIFY_LA2 (name, age=20, *args, **kwargs): Print (' name= ', name) print (' age= ', ' Age ') (' args= ', args) pr Int (' kwargs= ', Kwargs) modify_la2 (' dage ', ' Men ', 175, skill= ' pain ', father= ' ADW ') # Run results name= dageage= menargs= (175,) kwargs= {' father ': ' Adw ', ' skill ': ' Pain '}


Vi. anonymous function lambda

The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.

The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.


Format:

Lambda [arg1 [, Arg2,..... argn]]:expression

#梯形面积公式: Resault = lambda x1, x2, H: (x1 + x2) *h/2print (Resault (1, 2, 4))


Python Basics: Python functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.