Introduction to the functions of Python basics

Source: Internet
Author: User
Tags define local function definition variable scope

A. function
A function is a function block that executes successfully or is required to inform the caller by the return value.

1. Function definition
def function name (parameter)
......
function body
......
return value

A. Creating a function with the DEF keyword
B. function name, which is followed by the function name, each function must have a name
C. function parameters, non-parametric functions and parametric functions (explained below)
D. function body, statement combination for function function
E. return value, return function execution result data to function caller

2. Use of functions
After the function is defined, the function body is not executed, and when Python interprets the function name defined by Def, it opens up a space in memory to put the function in, the function name as the variable points to the memory space, and the function executes the function body when it is called. When executing a function body, once executed to the return statement, the function execution terminates immediately (even if there are still statements in the function body) return the value to the calling function, if there is no return statement in the function body, the default returns none to the calling function.


3. Parameters of the function
The function is divided into the parameterless function and the parameter function, when the function is defined, if the parameter unification is called the formal parameter, the argument passed when the function is called is called the actual parameter.


3.1 General parameters


function defines a few parameters, in the call will need to pass a number of parameters (except for the default values in the formal parameters), the transmission of more or less in the execution of the error, passing the argument is the default and parameter one by one corresponding.

#普通参数
def send (F1,F2): #定义了2个形参
#函数体
Print (F1,F2)
Return True

Em=input (' Please enter e-mail address: ')
Result=send (em, ' hello ') # requires passing 2 arguments
if result = = True:
Print (' Send success ')
Else
Print (' Send failed ')

3.2 Default Parameters

Parameters in the parameter have default parameters, if the default parameters are set, then the default parameters must be placed in the last side of the parameter list;

#默认参数, the call can not pass the value, you can also pass the value from the new
def send (f1,f2,xx= ' OK '): #位置参数要在关键字参数前面, the default parameter can be passed or not when called

#函数体

Print (F1,F2,XX)

Return True

Em=input (' Please enter e-mail address: ')

Result=send (em, ' hello ') #传递2个实参, does not change the value of the default parameter

Re=send (em, ' hel ', ' NO ') #传递3个实参, change the value of the default parameter

if result = = true and re = = true:

Print (' Send success ')

Else

Print (' Send failed ')


3.3 Specifying parameters

#指定参数

def send (f1,f2,xx= ' OK '):

#函数体

Print (F1,F2,XX)

Return True

Em=input (' Please enter e-mail address: ')

Re=send (f1=em,f2= ' hel ', xx= ' NO ') #调用的时候指定参数值, the parameter name must be identical to the formal parameter (order to not be consistent)

if re = = True:

Print (' Send success ')

Else

Print (' Send failed ')


3.4 Dynamic Parameters
The 3.4.1 parameter is preceded by a * parameter

If you add a * before the formal parameter, then it is the progenitor, you can receive any actual parameters (the parameter is preceded by an * number, when the call of the parameter can receive the argument of the pass, without error); If there is a * in front of the argument passed at the time of the call, Then it is to take each element in the argument out of the parameter that is assigned to the function as an element, and if the call is not preceded by a * is to pass the meta Sojitsu parameter as a child ancestor to the formal parameter.

def func (*args):

Print args

# execution Mode One

Func (11,33,4,4454,5)

# Execution Mode II

Li = [11,2,2,3,3,4,54]

Func (*li)


3.4.22 * Parameters

Two * * parameters, is the dictionary, if you add two * * before the formal parameter, then it is a dictionary, and when the call needs to specify K and V, then the parameter call can only be called or passed with the specified parameters before the argument is 2 * (the argument must be a dictionary), then the argument is assigned to the function parameter, such as:

def func (**kwargs):

Print args

# execution Mode One

Func (name= ' Wupeiqi ', age=18)

# Execution Mode II

Li = {' name ': ' Wupeiqi ', age:18, ' gender ': ' Male '}

Func (**li)

3.4.3 Universal Parameters
def fname (*args,**kwargs) #只能一个 * in front, 2 * in the back

Print (args)

Print (Kwargs)

fname (11,22,33,k1= ' v1 ', k2= ' v2 ')

3.5 Implementing the Format function with dynamic parameters
Format functions as: Format (*args,**kwargs)

1) Position parameters

Fstr= ' I am {0},my is {1} ' #这里的0和1代表第几个参数

Print (Fstr.format (' Alex ', 22))

Li= (' Alex ', 33)

Print (Fstr.format (*li))

2) Variable parameters

Fstr2= ' I am {name},my age} '

Print (Fstr2.format (name= ' pwj ', age=21))

ld={' name ': ' Sindy ', ' Age ': 18}

Print (Fstr2.format (**LD))


4. Global variables

A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable.
The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable.
When a global variable has the same name as a local variable:
Local variables work in sub-programs that define local variables, and global variables work elsewhere.
Global variables, default with uppercase variable names
To re-assign a global variable, you need to first

Name= ' WPJ ' #全局变量

Age=22

Def f1 ():

Global age #先global, and re-assign values

Age=22 #x修改全局变量, Front plus global

Name= ' Alex ' #这是局部变量, which only takes effect in this function, takes precedence over the use of your own

Print (name)

def f2 ():

Print (name) #引用的是全局变量

F1 ()

F2 ()

5. Ternary operation
is if. else.. The shorthand,
Res= 1 If True else 2 if the condition after the if is true then Res=1, otherwise res=2


6.lambda expression (anonymous function)
anonymous function, a lambda followed by a colon preceded by a parameter (can be multiple), followed by a colon is the function body (a sentence) implies the return function, for example: F2=lambda a1,a2:a1+a2+100

7. Introduction to commonly used built-in functions
ABS () #取绝对值

All (Iteration object) #一个为假, the result is false, all ([11,22,33,0]) result is false

Any (Iteration object) #, one is true, the result is true, any ((22, (), 0)) The result is true

Bin () #把十进制转换成二进制, print (Bin (5)) #结果: 0b101

Oct () #把十进制转换成八进制, Print (Oct (9)) #结果: 0o11

Hex () #把十进制转换成十六进制, print (hex) #结果0xe

ASCII () #自动执行对象的__repr__方法

Callable () #判断对象是否是可调用对象


Introduction to the functions of Python basics

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.