Python Basics-Functions

Source: Internet
Author: User
Tags define local variable scope

Definition: A function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functions
Characteristics:

1. 减少重复代码2. 使程序变的可扩展3. 使程序变得易维护

In Python, define a function to use the DEF statement, write down the function name, parentheses, the arguments in parentheses, and the colon: and then, in the indent block, write the function body, and the return value of the function is returned with a return statement.
function classification
Built-in functions
Custom functions
The Python interpreter already has a function defined for us as a built-in function.
Functions that can be used directly, such as Len (), sum (), Max ()
Custom Function 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, and the parentheses can be used to define the 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.
#语法
def function name (parameter 1, parameter 2, Parameter 3,...):
"' Notes '
function body
Return the value returned by
def hello ():
Print ("Hello word")
Hello ()

In Python, a function must be defined before it can be called
def hello ():
Print ("Hello")
Word ()
Hello ()

def hello ():
Print ("Hello")
Word ()
Hello ()
def word ():
Print ("word")
Error word not defined

def hello ():
Print ("Hello")
Word ()

def word ():
Print ("word")

Hello ()
Normal operation

You can divide the function into two parts.
Definition of a function
Call to function
Parsing a function when defined, without executing a function
Detect if logic returns results correctly when called

The above is a function without parameters
and a function with parameters.
Def mysum (A, B):
res = a + b
Print (RES)
MySum (ON)
A, B is called formal parameters (arguments when the function is defined)
Called arguments (parameters passed when a function call)
The formal parameter (variable) allocates the memory unit only when it is called, and immediately releases the allocated memory unit at the end of the call. Formal parameters are valid only within the function. The parameter variable can no longer be used after the function call finishes returning the keynote function.
Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of arguments, and they must have a definite value when making a function call to pass these values to the parameter. Therefore, you should use the assignment, input and other methods to get the parameters to determine the value

Default parameters
If there is a parameter that is the same or is seldom changed to be written as a default parameter
For example:
def register (name,age,country= "CN"):
Print (name)
Print (age)
Print (name)
Print (country)
Register ("Jack", 16)
Register ("Mike", "USA")


The operation results are as follows

Keyword parameter (key-value pair parameter)
Under normal circumstances, to pass parameters to the function in order, do not want to order the key parameters can be used, just specify the parameter name, keyword parameters must be placed after the position parameter.


Results


Summarize:
First, Position parameters
Parameters are passed when the function is called based on the parameter position defined by the function
Second, keyword parameters
For function calls, specified by key-value form. It can make the function clearer and easier to use, and also clears the order requirements of the parameters.
Third, default parameters
Used to define a function, to provide a default value for the parameter, to invoke the function can be passed the value of the default parameter (note: All positional parameters must appear before the default parameters, including function definitions and calls)
Use of default parameters: Just a few of the parameters need to be modified!
The default parameters and positional parameters exist at the same time, to put the default parameters in the back ah, put in front of the words, if only pass a parameter in, the compiler does not know who you are.
The default parameter cannot be a mutable object. Because mutable objects are likely to change in values in a function, they are not the default values.
Non-fixed parameters (variable parameters)
If the function does not determine how many parameters the user wants to pass in the definition, it can use the non-fixed parameter

Results

An empty tuple if the variable parameter does not pass arguments

def register (Name,age,args): # args turns multiple incoming parameters into a tuple form
Print (Name,age,args)
Register (' Jack ', ', ' python ', ' php ', ' Java ')
Register (' Mike ', 18)

can also have a *Kwargs
Kwargs will turn multiple incoming parameters into a dict form.
#如果为空则返回空元组 Empty Dictionary



Kwargs will turn multiple incoming parameters into a dict form.
def register (Name,age,
Args,**kwargs):
Print (Name,age,args,kwargs)
Register ("Jack", sex=, "CN", "Python", "Male", province= "Jiangsu")
#如果为空则返回空元组 Empty Dictionary
Register ("Mike", 16)
Parameter combinations
In particular, it is often used more than one parameter. These parameters are in order:
Positional parameters, default parameters, variable parameters, key-value pairs parameters (keyword parameters)

Local variables

Global variables can be used inside a function
If the assignment changes inside the function, it only works inside the function.


The results are as follows:

Name = "I am a global variable"
def change_name (name):
Print ("Use passed global variable:", name)
Name = "I am a local variable of a function"
Print ("Use variables inside function", name)
Change_name (name)
Print ("External print:", name)

Global vs. local variables
A variable defined in a function is called a local variable (for this function), and a variable defined outside the function is called a global variable (acting on the entire program).
A global variable scope is the entire program, and the local variable scope is the function that defines the variable.
When a global variable has the same name as a local variable:
Local variables work within functions that define local variables, and global variables work elsewhere.

Scope
A new scope is created in the Python function and only works within the function body
When a variable is encountered in the body of a function, Python will first look for the variable name in the function's namespace, and if it cannot find the global variable
STRs = "TestString"
Print (ID (strs))
def foo ():
Print (STRs)
Print (ID (strs))
Foo ()
Print (ID (strs))


You can see that the address does not change
What happens if I re-assign a value inside a function?

STRs = ' abc '
Print (ID (strs)) #abc的地址
def foo ():
STRs = ' CDE '
Print (ID (strs)) #输出新创建的地址
Print (STRs) #新创建的地址的内容即cde
Foo ()
Print (ID (strs)) #全局变量abc的地址
Print (STRs) #全局变量不会改变

Output results

All variables can be accessed (if they are mutable types and can even be modified). Foo (), in effect, creates a local variable with the same name as the global variable in the stack, which can be verified by printing the local namespace in function foo. After the function finishes executing the output global variable can be seen that the value of the variable STRs in the global namespace does not change the address.

Python Basics-Functions

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.