Python3 Basics-function

Source: Internet
Author: User
Tags closure

Ython function

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.

Defining functions
def functionname():"Function _ Document String"return[expression]

A function document is similar to a comment, which is used to understand function functions. You can use functionname.__doc__ to print out the contents of a function document.
Calling functions
#!/usr/bin/python #-*-Coding:utf-8-*- # define functions def Printme ( str   print Str;return; # call function printme ( "I want to invoke a user-defined function!") printme ( "call the same function again"      

Note: Forward references are not allowed in Python, that is, the function is not allowed to be called until the function is defined. That is, the function must be defined before the function is called.

function parameters

First understand the concepts of the following formal parameters and arguments:

The parameters in the function definition procedure are called parameters, and the arguments passed in when the function is called are called arguments, which are the specific parameter values.

There are four types of function definition parameters:

1. Position parameters

The required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.

2. Default parameters

Parameters are assigned initial values during parameter definition, and when the function is called, the default value is used instead of assigning a value to the parameter.

3. Keyword parameters

Parameters that need to be assigned are specified by the parameter name, and the order of arguments is not consistent with the declaration when using the keyword argument, because the Python interpreter can match the parameter value with the name of the argument.

def printme():"Print any incoming string" Print str;  return;  #调用printme函数printme(="My string");          

4. Variable parameters (collect parameters)

def functionname([Formal_args,]*):"Function _ Document String"return[expression] 

Variable names with an asterisk (*) will hold all unnamed variable arguments. In fact, Python is a collection of parameters as a tuple processing.

If you need to add additional custom parameters after collecting the parameters, you will need to assign values using the keyword parameter when assigning them. Try to set default values for these custom parameters when defining functions, preventing errors.

function return value

Def back ():

return [1, ' s ', 2]

Def back ():

Return, ' s '

Multiple data separated by commas, in fact, to return a tuple

function Scope

Global variables VS Local variables

We usually make variables defined outside the function as global variables, variables defined within the function are called local variables, and as the name implies, the scope of the global variable is the entire code snippet, and the scope of the local variable is only in the code segment to which it belongs, and the variable is only valid in its scope.

Note: Global variables can be accessed within a function, but cannot be modified. If you forcibly modify a global variable, Python automatically creates a local variable with the same name as the global variable within the function, and the local variable is modified, and the global variable does not change.

Global keyword

As you can see from the code in the above lesson, if the variable name declared in the function is duplicated with the existing global variable name, then the local variable overwrites the global variable. If you want to use global variables in the body of a function, you need to use the global statement to declare the variable that is used before it is a globally variable.

inline functions

Internal functions The entire scope is within the outer function

Def fun1 ():
Print (' fun1 () is being called ... ')
Def fun2 ():
Print (' fun2 () is being called ... ')
Fun2 ()
FUN1 ()

FUN1 () is being called ...
Fun2 () is being called ...

Fun2 ()

Error, hint fun2 not defined

Intrinsic functions can only be called within the body of an external function, and will be an error if used outside the external function.

Closures (closure)

If, in an intrinsic function, a reference is made to a variable in the outer scope, then the intrinsic function is a closure

def funx (x):
def funy (y):
Return X*y
Return Funy

Funx (3) returns the function type

Print (Funx (3) (4)) prints out 12

Def fun1 ():
Def fun2 ():
return x
Return fun2 ()
FUN1 () error, because in fun2, the variable x that called and changed the external function

Def fun1 ():
Def fun2 ():
nonlocal x
return x
Return fun2 ()
Print (FUN1 ()) to perform normally

Lambda expression (anonymous function)

The main function is to simplify the code, not to mention the problem of function names.

Python3 Basics-function

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: 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.