Python3 function,

Source: Internet
Author: User

Python3 function,
1. python3 Function

Functions are organized and reusable, and used to implement a single, or associated function code segment.

Functions can improve the app's vigilance and reuse of code. You can create a function by yourself, which is called a user-defined function.

1. Define function rules
  • Function Code BlockDefStarts with a keyword, followed by a Function Identifier name and parentheses().
  • Any input parameters and independent variables must be placed in the middle of the parentheses, which can be used to define parameters.
  • The first line of a function can selectively use the document string-used to store the function description.
  • The function content starts with a colon and is indented.
  • Return [expression] ends the function and returns a value to the caller selectively. Return without expression is equivalent to return None.
2. Syntax

The definition function of python uses the def keyword in the following format:

Def function name (parameter list ):

Function body

>>> Def hello (): # define a simple function... print ('Hello World')... >>> hello () # execute the function hello world >>> def yourname (name): # pass the parameter function... print ('your are name is: ', name)... >>> yourname ('qi ') # Run the parameter passing function your are name is: qi >>> def multiplication (x, y): # The parameter passing function... return x * y... >>> multiplication (8, 9) 72
3. function call

Define a function: Give the function a name and specify the parameters and code block structure contained in the function. After the basic structure of this function is completed.

It can be executed through another function call or directly from the python command prompt.

>>> Def times (date ):... 'print current Time '... print (date );... return time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime ()... >>> import time >>> times ('current time is ') current time is '2017-09-30 23:23:27'
4. parameter transfer

In python, the type is an object and the variable is of no type.

Mutable and immutable objects

In python, strings, tuples, and numbers are unchangeable objects, while list and dict are modifiable objects.

  • Unchangeable type:Variable assignmentA = 5Then assign a valueA = 10Here, we actually generate an int value object 10, and let a point to it, and 5 is discarded, instead of changing the value of a, which is equivalent to generating.

  • Variable type:Variable assignmentLa = [1, 2, 4]Then assign a valueLa [2] = 5It is to change the value of the third element of list la, la itself is not dynamic, but a part of its internal value is modified.

Passing parameters of python functions:

  • Unchangeable type:It is similar to the value transfer of c ++, such as integers, strings, and tuples. For example, fun (a) only transmits the value of a, without affecting the object itself. For example, modifying the value of a in fun (a) is only modifying another replicated object and does not affect.

  • Variable type:Similar to c ++, such as list and dictionary. For example, fun (la) is to pass la to the real end. After modification, la outside fun will also be affected.

Everything in python is an object. Strictly speaking, we can't say whether to pass values or references. We should say that immutable objects and variable objects are passed. Immutable instance:

>>> Def changeint (x): # define the function to assign values to parameters... x = 100...> i1 = 200 >>> changeint (i1) # When the defined variable is assigned to the function call, the original variable remains unchanged, but the i1 variable value is copied to x, they both point to this object. >>> Print (i1) 200

Upload a variable object instance:

If a variable object modifies a parameter in a function, the original parameter is also changed in the function that calls the function.

>>> Def changelist (l1, v): # define the list insertion function... l1.insert (2, v )... return l1.... >>> list1 = [1, 2, 4] # list >>> changelist (list1, 'python') # The list outside the application will affect the content of the list outside the application [1, 2, 'python', 3, 4] >>> print (list1) # The list content is changed to [1, 2, 'python', 3, 4].
5. Parameter type

Required parameter: When a function requires a parameter, the parameter must be specified when the function is executed; otherwise, an error is reported.

Keyword parameter: when you use a keyword to pass a parameter, the parameter order can be arbitrary, and the interpreter will match the parameter name for passing.

Default parameter: When a function is called, if no parameter is passed, the default parameter is used.

Variable Length parameters: for example, when passing a list, ancestor, or dictionary, the number of parameters is variable length. You can use (*) to indicate the variable length,

>>> Def foo (user): # required parameter... print (user, 'travel ')...> foo ('zhang san') Zhang San travel >>> foor () # If no parameter is passed, the error Traceback (most recent call last) will be reported if the function is executed: File "<stdin> ", line 1, in <module> NameError: name 'foor' is not defined> def foo (user, action ):... print (action, '', user) # PASS Parameters to function entities by using keywords, so you do not have to call them in order... >>> foo ('Li si', 'work') goes to work to Li Si> def foo (user, action = 'beijing'): # define the default parameter which must be defined at the end... print (user, 'from', action)...> foo ('hangsan', 'shanghai') # If specified, the output value of zhangsan is from shanghai >>> foo ('hangsan ') # If a parameter is specified, the default shangsan is from Beijing> def foo (user, where = 'beijing', action = 'travel '): # define the default parameter... print (user, 'delet', where, action)...> foo ('zhangsan', 'shanghai', 'gongzuo') # specify the parameter to output zhangsan to shanghai gongzuo >>> foo ('lisi ') # If only one parameter is specified, use the default parameter lisi to travel to Beijing >>> foo ('lisi', action = 'work') # when there are multiple default parameters, you must specify the parameter name to transfer the parameter lisi to Beijing for work> foo ('lisi', where = 'shanghai', action = 'learn ') lisi go to Shanghai to learn >>> def show (* args): # variable length parameter... for I in args :... print (I)... >>> show ('hangsan', 'lisi', 'hangzhou') zhangsanlisiwangwu >>> l1 = [1, 2, 3, 4] >>> show (l1) [1, 2, 3, 4] >>> show (* l1) # If you want to pass parameters in the list, you must use * for variable-length parameter passing 1234 >>> def show (** kargs ): # Two parameters may not be long-passed parameters, that is, dictionary-based parameter passing... for I in kargs. items ():... print (I)... >>> show (name = 'hangsan ', age = 9999) ('age', 9999) ('name', 'hangsan') >>> dict = {'k1': 123, 'k2': 456, 'k3 ': 678 }>>> show (dict) # When passing the parameter dictionary, the dictionary will be used. When passing in a parameter, the error Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: show () takes 0 positional arguments but 1 was given >>> show (** dict) # parameters must be separated using (**) ('k1 ', 123) ('k2', 456) ('k3 ', 678)
6. return Statement

The return [expression] statement is used to exit a function and selectively returns an expression to the caller. The return statement without the Parameter Value Returns None.

>>> Def foo ():... 1 + 1... return...> print (foo () # NoneNone >>> def foo ():... 1 + 1... return 0 # specify the return value... >>> print (foo () 0 >>> def foo ():... return 1 + 1... >>> print (foo () 2 >>> def foo ():... print (1 + 1 )... return 1 + 2... >>> print (foo () 23
7. variable scope

In Python, the variable of the program is not accessible anywhere. The access permission determines where the variable is assigned a value.

The scope of a variable determines which specific variable name the program can access. Python has four scopes:

  • L (Local) Local scope
  • E (Enclosing)
  • G (Global) Global SCOPE
  • B (Built-in) built-in Scope

Search by the L-> E-> G-> B rule, that is, if the local location cannot be found, the local location will be searched (such as the closure ), if you cannot find it, you will find it globally, and then you will find it in the inner process.

>>> M = 'girl '# global scope variable >>> def func ():... m = 'boys' # local scope variable... return m...> func () # prioritize the use of the local scope variable 'boys'> print (m) # but does not change the global scope variable girl >>> def foo ():... num = x + 100 # If the variable x is not defined, an error is reported... return num...> foo () Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in fooNameError: name 'X' is not defined >>> x = 11 # define a global variable >>> foo () # The function calls the global variable 111> num = 100> def func ():... num = 200... x = num + 100... return x...> func () 300 >>> n = 10 # global >>> def foo ():... global n # Use global to define a local variable as a global variable and overwrite the previous variable value... n = 100... return n... >>> foo () 100 >>> print (n) # The global variable value changes 100 >>> def foo (): # defines a nested function... num = 5... def bar (): # nested use of closure scope variables... print (num )... bar ()... print (num)... >>> foo () 55 >>> def foo ():... num1 = 20... def bar ():... z = 30... print (num1 )... bar ()... print (z)... >>> foo () 20 Traceback (most recent call last): # When the nested closure scope is undefined, the File "<stdin>", line 1, in <module> File "<stdin>", line 7, in fooNameError: name 'Z' is not defined >>>> def foo ():... m = 111... def bar ():... n = 222... print (m + n) # in the bar () function, m is a closure variable that is neither fully local nor local. It exists in the namespace and scope of a function, that is, nested scope... bar ()... print (m)... >>> foo () 333111def foo (): num2 = 400 def bar (): print (num2) num2 = 333 print (num2) bar () foo () Traceback (most recent call last): # The error cause is that num2 is of an unchangeable type. You cannot redefine File "<stdin>", line 1, in <module> File "<stdin>", line 7, in foo File "<stdin>", line 4, in barUnboundLocalError: local variable 'num2' referenced before assignmentdef foo (): num2 = [400] def bar (): print (num2 [0]) num2 [0] = 333 # If it is defined as a list, print (num2 [0]) bar () foo () 400333 is not reported
Ii. Anonymous Functions

Python uses lambda to create anonymous functions.

The so-called anonymity means that a function is no longer defined in the standard format of def statements.

  • Lambda is just an expression, and the function is much simpler than def.
  • The body of lambda is an expression rather than a code block. Only limited logic can be encapsulated in lambda expressions.
  • Lambda functions have their own namespaces and cannot access parameters outside their parameter lists or in global namespaces.
  • Although lambda functions seem to be able to write only one row, they are not equivalent to C or C ++ inline functions. The latter aims to call small functions without occupying the stack memory to increase the running efficiency.
1. Syntax

The syntax of the lambda function only contains one statement.

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

>>> Funct1 = lambda x, y: x + y # generate an anonymous function >>> print (funct1 (10, 43) 53 >>> funct2 = lambda x: x ** 3> print (funct2 (2) 8> funct3 = lambda x, y = 3, z = 4: you can set the default value for the x + y + z # parameter> print (funct3 (3) 10> print (funct3 (3, 4, 5 )) 12 >>> print (funct3 (3, y = 9) # specify the parameter name 16 when passing values through multiple parameters >>> print (funct3 (3, z = 8, y = 9) 20 >>> list (map (lambda x: x ** 3, [1, 3, 4, 5]) # generate a sequence of map [1, 8, 27, 64,125] >>> list (map (lambda x, y: x + y, [,], [,]) # Pass values to multiple parameters, otherwise, take the minimum value as the standard [12, 24, 36, 48] >>> list (map (lambda x: x + 5), range (10 ))) # Use the iterator [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> l1 = [(lambda x: x + 5 ), (lambda x: x ** 2), (lambda x: x/2)] # generate a variable list> print (l1 [0] (5 ), l1 [1] (3), l1 [2] (10) 10 9 5.0 >>>> dict1 = {'k1 ':( lambda x: x ** 2 ), 'k2' :( lambda x: x ** 3), 'k3 ':( lambda x: x ** 4) >>> print (dict1 ['k1 '] (2), dict1 ['k2'] (2), dict1 ['k3'] (2) # generate a variable dictionary 4 8 16

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.