Python Learning Notes (iv)-functions

Source: Internet
Author: User

What is a function?

The term function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, and the function in programming has many different names in English. In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called method.

Definition: A function is a collection of a set of statements by a name (function name) encapsulated, in order to execute this function, just call its function name.

II. Benefits of using functions:

1. Simplified code
2, improve the reusability of code
3, code can be extended

Third, the definition of functions in Python:

The definition function uses the DEF keyword, followed by the function name, the function name cannot be re -complex, the function does not call will not be executed

def Fun ():  #  defines a function, followed by the letter    print("HelloWorld"   #  function Body fun ()# Call function

Iv. parameters of the function

1. When the function is called, it can pass in parameters, tangible parameters and actual arguments.

Formal parameters:

Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function.

Actual parameters:

Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. The parameter variable can no longer be used after the function call finishes returning the keynote function.

def Calc (x, y):  #  defines a function with parameters x and Y,x and y is the formal parameter    print(x * y)  #  Output x multiplied by Y value Calc (5, 2)  #  Call the functions defined above, 5 and 2 are arguments

2, the function of the four types of formal parameters:

Position parameters:

Positional parameters, which are literally meant to be passed as parameters, such as the Calc function above, where x and y are positional parameters, the positional parameters must be passed,

There are several positional parameters at the time of the call to pass a few, otherwise it will be error, if there are multiple positional parameters, you can not remember which location to pass what to do, you may use the name of the positional parameter to specify the call

For example, the Calc function above can also be called by using Calc (y=1,x=2), which is called the keyword argument.

Default parameters:

The default parameter is when you define formal parameters, assign a value to the function by default, such as the port of the database, the default is to give it a value, so that even if you do not pass this parameter in the call, it is also a value

So, the default parameter is not required, and if you pass the value to the default parameter, it will use the value you passed in. If a default value parameter is used, it must be defined after the position parameter.

def Calc (x, y=0):  #  y is the default parameter, not required; X is the positional parameter, required    print(x * y) Calc (5, 2)  

Non-fixed parameters:

The above two positional parameters and the default parameters are the number of parameters is fixed, if I am a function, the parameters are not fixed, I do not know the future of this function will expand into what kind of, may be more and more parameters, this time if the fixed parameters, then the program is not good expansion, then you can use non-fixed parameters, There are two types of non-fixed parameters, one is a variable parameter and one is a keyword parameter.

1) Variable parameters:

Variable parameters are received with *, the number of arguments to pass after the number of passes, if the positional parameters, default parameters, variable parameters used together, the variable parameter must be in the position parameter and the default value parameter. Variable parameters are also non-mandatory.

def More_arg (name, age, sex='nan', *agrs):  #  positional parameter, default value parameter, variable parameter, The variable parameter will put the parameters of the subsequent passes into the tuple of args ,    print(name, age, AGRs) more_arg ('Marry ' ' NV ' ' python ' '  China ')  # called

2) keyword parameters:

Keyword parameter use * * to receive, the following parameters are not fixed, want to write how many write how many, of course, can also be used with the above several, if you want to use the keyword parameter must be in the last side.

With keyword arguments, you must use the keyword argument when calling. Keyword parameters are also non-mandatory.

def kw_arg (name, **kwargs):  #  positional parameter, keyword parameter, when called, will put the passed keyword parameter into kwargs this dictionary     Print(name, Kwargs) kw_arg ('sriba', sex=' m '  , age=18)  #  call, sex and age are the keyword calls

V. Return value of a function

Each function has a return value, if it is not specified in the function of the return value, after the function is executed in Python, the default will return a none, the function can have more than one return value, if there are multiple return values, the return value will be placed in a tuple, the return is a tuple.

Why should there be a return value, because after this function is finished, its result will need to be used in the later program.

The return value in the function uses return, and the function ends immediately when it encounters a return.

def Calc (x, y):  #  This is the definition of a function with a return value    c = x *    yreturn  = Calc (5, 6)  #  assigns the return result of the function to the resprint(res)

Vi. local variables and global variables

Local variable meaning is in the local effect, out of the scope of the variable, this variable is invalid, such as the above C is a local variable, after this function, there is no C this value

Global variables mean that the whole program is in effect, in the first definition of the program is the global variables, global variables if you want to modify in the function, you need to add the Global keyword declaration, if it is a list, dictionary and collection, you do not need to add the global keyword, directly can be modified.

 a=100#   global variable  def   Test ():  global  a #   Declaring a global variable, the local variable changes the outside global variable  a=5#   inside the function is a local variable  print  ( '   Inside the   " ,a)  def   Test2 (): b  =1 print   (a) test () test2 ()  print  (" Span style= "COLOR: #800000" > outside of   ", a) 
a=100def  test2 ():    Global  a    print(a)# This is a global variable a= 100, if a is not declared as a global variable, then local variable A does not define an error    a=1    print(a)# This is a changed global variable a=1, Local variable if no global variable is declared a=1test2 ()print(a)# This a global variable

Vii. Recursive invocation

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

Recursive invocation means, within the function itself calls itself, a little loop meaning, write a recursive, as follows:

deftest1 (): Num= Int (Input ('Please enter a number:'))    ifNum%2==0:#determine if the number entered is even       returnTrue#if it is an even number, the program exits and returns True.    Print('not even please re-enter! ')    returnTest1 ()#if it is not even, continue calling yourself, enter the valuePrint(Test1 ())#Call Test" "there must be a definite end condition that can be achieved with recursion, and the loop can be implemented, preferably recursive to a low recursion rate of up to 999 times" "

Python Learning Notes (iv)-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.