Python function 01

Source: Internet
Author: User

Python functions

Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.

Functions can improve the modularity of the application, and the reuse of the code. You already know that Python provides a number of built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.

Define a function

You can define a function that you want to function, and here are the simple rules:

    • The function code block begins with a def keyword followed by the function identifier name and parentheses ().
    • Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
    • The first line of the function statement can optionally use the document string-for storing the function description.
    • The function contents begin with a colon and are indented.
    • return [expression] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.
Grammar
def functionname():"Function _ Document String"return[expression]     
1. Simple function definition and invocation
# !/usr/bin/env python # -*-coding:utf-8-*- def # function Definition    Print ("helloWorld"# function within the statement func ()  # function Call # running results Hello World
2. Simple Parameter transfer

Formal parameters: When defining a function, the parameter defined is called a formal parameter.

Actual arguments: When a function is called, the passed argument is called an argument.

# !/usr/bin/env python # -*-coding:utf-8-*- def # function definition, defining a formal parameter    Print # the statement func within the function (" This is a parameter I passed ")  # function call #  Running Results This is a parameter I passed.
3. return value of function

1, function encountered return does not continue to execute, directly jump out of the function.

2. The return value can be passed to the caller.

3, return statement [expression] exits the function, optionally returning an expression to the caller. Return statement with no parameter value returns none

# !/usr/bin/env python # -*-coding:utf-8-*- def func (A, b):  #  function definition, define two parameter return     A + b  #  return a + The value of B to the function caller  = func  #  function call, defining a variable to accept the return value print  num  #  Run result 3
4. Keyword parameters

1. The key parameter and function call are closely related, and the function call uses the keyword parameter to determine the passed parameter value.

2. The order of parameters is not consistent with the declaration when using the keyword parameter, because the Python interpreter can match the parameter value with the name of the argument.

#!/usr/bin/env python#-*-coding:utf-8-*-defFunc (A, B):#function definition, defining two parameters    Print(A, B)#statements within a functionfunc (b=" World", a="Hello")#function Call#Run Results('Hello',' World')
5. Default parameters

1. If no actual parameters are passed for the formal parameter, the parameter uses the default value.

2, in this case, specify the default value of the parameters must be written on the last side, or will be an error.

#!/usr/bin/env python#-*-coding:utf-8-*-defFunction4 (A, b="Good"):#The default value for definition B is good, and if a function call does not pass a parameter for B, the default value is used    returnA +bPrintFunction4 ("Hello")PrintFunction4 ("Hello","Xiao Ming")#Operation Result:Hello good hello, xiaoming .
6. Variable length parameter (*)

1, the function can accept any number of parameters, the function by default will put all the parameters in a tuple, each parameter as an element of the tuple, function declaration is not named.

2. Variable names with asterisks (*) will hold all unnamed variable arguments.

3, if there is a real formal parameter, will pass the parameters passed in once to the defined formal parameters, the other parameters are * received.

#!/usr/bin/env python#-*-coding:utf-8-*-deffunction (b, *a):#can be declared along with common parameters    Print("This is the first parameter that is passed in:%s This is the other parameter that is passed in:%s"%(b, a))returnfunction (1) function (1, 2) function (1, 2, 3,"a","b","C")#Run ResultsThis is the first parameter passed in: 1This is the other parameter that is passed in: () This is the first parameter that is passed in:1 This is the other parameters that are passed in: (2,) This is the first parameter that is passed in:1 This is the other parameters that are passed in: (2, 3,'a','b','C')
7, variable length parameters (* *)

The passed-in parameter must be passed as Key = value and can be passed as many as possible, and the function will keep the passed-in parameters in the dictionary, each as a set of elements of the dictionary.

#!/usr/bin/env python#-*-coding:utf-8-*-deffunction (* *a):PrintA, type (a) function (AA="AA", bb="BB")#Run Results{'AA':'AA','BB':'BB'} <type'Dict'>
8, variable length parameters (*) (* *)

1、此种情况任何参数都可以传递,但是如果有普通的形参(k),传递的第一个参数一定会给k。

2、此种情况 **b一定要放在最后,*a放在**b之前。

#!/usr/bin/env python#-*-coding:utf-8-*-deffunction (k, *a, * *b):PrintkPrintA, type (a)PrintB, type (b)returnfunction (1, 2, 3,"a","b", ("Hello"," World"), aa="AA", bb="BB")#Run Results1(2, 3,'a','b', ('Hello',' World')) <type'tuple'>{'AA':'AA','BB':'BB'} <type'Dict'>
9. Global variables and local variables

1. Local variables: variables declared within a function, used inside the function.

2, global variables: variables declared in the global, all can be used.

3, the recommended global variable all uppercase, local variable all lowercase.

4. The default function can call global variables, and you cannot modify global variables.

5. If you want to modify global variables within a function, you can declare the variable as a global variable and then modify it.

 #  !/usr/bin/env python  #  -*-coding:utf-8-*- def   Func1 (): A  = print   AA  = 10func1 ()  print  Span style= "COLOR: #000000" > a  #   run Result:  3010#   above results show that the global variable cannot be modified by default within a function. 
# !/usr/bin/env python # -*-coding:utf-8-*- def func1 ():     Global a     =    print=func1 ()print  a#  Run result 3030#  If you modify a global variable inside a function, you need to declare the variable as a global variable inside the function with the global keyword. 
9. Can change (mutable) and non-change (immutable) objects

In Python, strings, tuples, and numbers are objects that cannot be changed, and List,dict are objects that can be modified.

    • immutable Type: variable assignment a=5 and then assign value a=10, here is actually reborn into an int value object 10, then a point to it, and 5 is discarded, not change the value of a, the equivalent of a new student into a.

    • Variable type: variable assignment la=[1,2,3,4] after assigning a value la[2]=5 is to change the value of the third element of List LA, itself LA is not moving, but its internal part of the value has been modified.

Parameter passing of the Python function:

    • immutable types: values such as C + + are passed, such as integers, strings, and tuples. such as fun (a), passing only a value, does not affect the A object itself. For example, in Fun (a) to modify the value of a, just modify another copy of the object, does not affect the a itself.

    • mutable types: references such as C + + are passed, such as lists, dictionaries. such as Fun (LA), is the real transfer of LA, the modified fun outside of LA will also be affected

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

Python-Pass Immutable object instance
# !/usr/bin/python # -*-coding:utf-8-*- def Changeint (a):     = Ten= 2changeint (b)print b  #  result is 2# Run result 2
The instance has int object 2, the variable that points to it is B, and when passed to the Changeint function, the variable b,a and B both point to the same int object, and at a=10, the new int value Object 10, and a points to it.

Python Transfer Variable object instance
#!/usr/bin/python#-*-coding:utf-8-*-#Writable Function Descriptiondefchangeme (mylist):"to modify an incoming list"Mylist.append ([1, 2, 3, 4]); Print "value in function:", MyListreturn#Call the Changeme functionMyList = [10, 20, 30];changeme (mylist);Print "values outside the function:", MyList#The same reference is used for the object passing in the function in the instance and adding new content at the end, so the output is as follows:#Run ResultsValues in function: [10, 20, 30, [1, 2, 3, 4] ] Outside the function: [10, 20, 30, [1, 2, 3, 4]]

Python function 01

Related Article

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.