Python function Basics---parameters, variables

Source: Internet
Author: User
Tags define local

Function: Refers to the collection of a set of statements by a name (function name) to encapsulate, to execute this function, just call its function name.

def sayhi (): # function name

Print (' Hello World ')

Sayhi() #调用函数, call the function with parentheses (), the memory address that defines the function name is called without adding

Example:

#普通代码:

A, B = 5,8 # This sentence means to assign values of 5 and 8, respectively, to the two variable, A/b, i.e. a= 8, b=8

C= a**b

Print (c)

#改成用函数写:

Def calc (x, y):

res = X**y

return res #返回函数执行结果

C= Calc (A, b) #结果赋值给c变量

Print (c)

Characteristics:

1. Reduce duplication of code

2. Make the program extensible

3. Make the program easier to maintain

Function parameters:

Parameters can make your functions more flexible and can also determine the execution flow within a function based on the difference in calling Shishun.

Shape parametric:

The memory unit is allocated only when it is called, and the allocated memory unit is freed at the end of the call. Therefore, the formal parameter is only valid inside the function. The parameter variable can no longer be used when the function call finishes returning the keynote function.

Actual parameters:

Can be constants, variables, expressions, functions, and so on, regardless of the actual argument is the type of amount, in the function call, they must have a certain value, in order to pass these values to the parameter, so the parameters should be pre-assigned, input and so on to get the value of the argument.

Such as:

Def calc (x, y): #x和y is the formal parameter

res = X**y

return res

C= Calc (A, b) #a和b就是实参

Print (c)

Default parameters:

As in the following program:

Found country This parameter is basically "cn", we can set the country as the default parameter, default to CN. Thus, when you do not specify this parameter at the time of invocation, the default is CN, which you specify, using the value you specify.

Such as:

Note: The position of the default parameter is placed after the positional parameter (in order of the parameters), preventing it from affecting other positional parameters.

Key parameters:

Under normal circumstances, to the function to pass parameters to order, do not want to order the key parameters, simply specify the parameter name at the time of invocation (the parameter named parameter is called the key parameter), but there is a requirement, the key parameter must be placed in the positional parameters (in order to determine the corresponding relationship parameters) after.

As in the following program:

This can be called when:

Course, age, and country are specified at the time of invocation, and they are the key parameters. Once specified, the function can be called according to the content specified by the key parameter, without having to assign a value to the parameter based on the location.

But this cannot be called:

Because ' PY ' specifies the parameter name course, and 22 does not specify an argument name, it is also a positional parameter, and the key parameter must be placed after the position parameter.

This is not the case:

Since 22 has been assigned an age of 22 according to the positional parameters, but the later age=25 is assigned a value of 25 to age, it is not possible to assign multiple values to the same parameter

Non-fixed parameters:

If your function is undefined, you can use a non-fixed parameter if you are unsure how many parameters the user wants to pass in.

defStu_register (Name,age,*args):#*args will turn the passed parameter into a tuple (Ganso ) Form    Print(Name,age,args) stu_register ('Alex', 22)#Output Result:#Alex () #后面这个 () is args, just because no value is passed, so it's empty.Stu_register ('Jack', 32,'CN','Python')#Output Result:#Jack (' CN ', ' Python ')

There's another one, **kwargs.

defStu_register (Name,age,*args,**kwargs):#**kwargs will change the number of arguments passed into a dictionary form.    Print(Name,age,args,kwargs) stu_register ('Jack', 32,'CN','Python')#Output Result:#Jack (' CN ', ' Python ') {} # after this {} is Kwargs, just because there is no value, so it is emptyStu_register ('Jack', 32,'CN','Python',gender='Male',province='Shandong')#Output Result:#Jack (' CN ', ' Python ') {' Gender ': ' Male ', ' Province ': ' Shandong '}

Note: agrs:arguments; Kwargs:key word arguments. If the parameter appears in front of the *, it becomes the progenitor; if the parameter is preceded by a * *, the parameter becomes a dictionary, or a dictionary (such as: info) can be passed directly into the Kwargs, but in the function call in front of the dictionary plus * * (such as **info)

In addition , a non-fixed parameter cannot be placed behind a positional parameter, but the key parameter can be located behind the *args parameter.

def stu_register (name,age,*args,gender):    print(name,age,args,gender) stu_ Register ('jack', +,'CN','Python  ', gender='male')#  output result:  #  Jack (' CN ', ' Python ') male

function return value:

Code outside the function to get the execution result of the function, you can return the execution result in the function with a return statement. (who calls it back to whom)

Such as:

defStu_register (name,age,course='Python', country='CN'):    Print('Student Information Form'. Center (50,'-'))    Print('Name:', name)Print('Age :', age)Print('Course:', course)Print('Country:', Country)ifAge >= 18:        returnTrueElse:        returnFalsestatus= Stu_register ('Wang Shanbao', 22,course='python full stack development', country='JP')#The program returns the execution result of true or false to the calling function and assigns a value to the variable status after the function stu_register is called.ifStatus:Print('Registration Successful')Else:    Print('too young to be old')

Note:

    • The function stops executing and returns the result as soon as it encounters a return statement, so can also be understood as a return statement that represents the end of the function

    • If return is not specified in the function, the return value of this function is None

    • Return can only return a value, if you want to return more than one value, you can add a comma (,) in the middle, but the returned value is in a meta Zuzhong (so return a value), if return is a list, then the result is a list (no longer ganso), Ganso return directly is the Yuan Zu

Local variables:

    • A variable defined in a function is called a local variable, and a variable defined at the beginning of a program is called a global variable
    • The scope of a global variable is the entire program, and the scope of the local variable is the function that defines the variable
    • When global variables and local variables have the same name, local variables work within functions that define local variables, and in other places global variables work. If the local variable has the same name as your global variable and the variable is not assigned within the function, then the local variable can call the value of the global variable, which means that the local variable takes precedence over the global variable within the function. But global variables cannot call local variables

If a global variable is a dictionary, a list, a collection, if a local variable with the same name within the function has been re-assigned, the local variable inside the function uses the value assigned within the function and does not affect the value of the global variable outside the function, if the local variable is not assigned to the function, And in the function of the increment, delete, modify, then the outside of the function of the global variable will also be added, deleted, modified. However, if the global variable is a string or a number, then the global variable cannot be changed by modifying the local variable.

If you have to modify global variables, use global, such as:

' Alexander ' def change_name ():     Global name    # Global variables are declared inside the function  ' Alex '    Print (name) change_name () Print (name) #  #Alex, Alex#

Note: Try not to declare global variables in the actual project using Global.

Python function Basics---parameters, variables

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.