My Python growth path---the third day---python Foundation---January 16, 2016 (haze)

Source: Internet
Author: User

Iv. functions

In daily life, to complete a complex function, we are always accustomed to the "big function" decomposition into a number of "small functions" to achieve. In the programming world, "function" can be called "function", so "function" is actually a piece of code that implements some function, and can be called by other code.

Suppose we need to calculate the area of the circle during the programming process. If we're not using functions, we need to do this every time we need to calculate the prototype area.

1 r1 = 12.342 r2 = 9.083 r3 = 73.14 s1 = 3.14 * R1 * R15 s2 = 3.14 * R2 * R26 s3 = 3.14 * R3 * R3

So if the number of calculations is relatively small, if you need to calculate a lot of times, it is more troublesome. In addition, if we want to change the formula, such as the value of π we want to change to 3.141592657, how many places to calculate how many times, trouble not to say, but also prone to errors, omissions and so on. function can effectively solve the above problems.

1. Definition and invocation of functions

Define a function to use the DEF keyword, write down the function name, parentheses, the arguments in parentheses, and the colon: and then use the indented code block to write the function body, the function body can call the return statement to return the result, in order to prototype area For example we can define a function like this

1 def Circle_area (R): 2     return 3.14 * R *r

So if we just call this function, we can do it.

1 circle_area (3)

So if we're going to change the value of π, we just need to change the function.

The function name is also used as the name of the function, and can be assigned as a variable, or even as a parameter, for example, we can also assign the function of the circular area to F, and then through F (4) to call the function, the meaning is the same.

1 f = circle_area2 F (4)
2. Parameters of the function

1) Position parameters

This is the most common way of defining a function that can define any parameter, separated by commas for each parameter, for example:

1 def Foo1 (Arg1, arg2): 2     Print (Arg1, arg2)

Functions defined in this way must also provide the number of equal values (actual arguments) in the parentheses after the function name, and the order must be the same, that is, in such a call, the number of formal parameters and arguments must be the same, and must be one by one corresponding, that is, the first parameter corresponds to the first argument. For example:

1 Foo1 ('abc', 123)

Output results

ABC 123

If the number of parameters and arguments is inconsistent, an error similar to the following will occur

Traceback (most recent):   " d:/oldboy_python_git/oldboy_python/day3/def_demo_4.py "  in <module>    foo3 ('abc'arg2  '

You can also pass parameters in the following way, regardless of the order, but the number must be the same anyway.

1 ' ABC ')

2) Default parameters

We can specify a default value for a parameter, and when it is called, the value of that parameter is equal to the default value if it is not specified.

1 def Foo2 (arg1, arg2 = 123):2     print(arg1, arg2)

Call

1 Foo2 ('abc')2 Foo2 ('ABC') , 345)

Execution results

ABC 123345

Note: The default parameter must be defined after all positional parameters, otherwise the syntax error will be reported.

def Foo2 (arg1 = 123, arg2):            ^syntaxerror:non-default argument follows default argument

3) Variable parameters

As the name implies, the variable parameter is the number of parameters passed in is variable, can be one, 2, or even 0

1 def Foo3 (*args):2     print(args)

Call

1 ' ABC ')

Execution results

' ABC ')

Note: You can see that we have passed three parameters that have been converted to Ganso by Python and saved to args, so that we can call the parameter memory by index, or iterate through for

4) keyword Parameters

Mutable parameters are assembled during the call process, and the Cheng Yuanju can only be called through an index, which is sometimes inconvenient, so Python assembles the passed-in parameters into a dictionary through the keyword index.

1 def Foo4 (* *Kwargs):2     print(Kwargs, type (Kwargs))34'  ABC', K2 = 123)

Execution results

{'K2'K1'abc'} <class  'dict'>

The keyword parameter allows parameters to pass in 0 or any parameter names, and 0 is an empty dictionary

3. Parameter combination

Defining functions in Python can be used in combination with required parameters (positional parameters), default parameters, variable parameters, keyword parameters, but the order must be required, default, variable, and keyword parameters.

1 defFoo5 (arg1, arg2 ='ABC', *args, * *Kwargs):2     Print('arg1:', Arg1)3     Print('arg2:', arg2)4     Print('args', args)5     Print('Kwargs', Kwargs)6 7FOO5 (123,'BCD', 123,'ABC', K1 = 123, K2 ='ABC')

Execution results

arg1:123Arg2:bcdargs ('abc') Kwargs {'K1'  'K2'abc'}
4. Lambda anonymous function

In Python, which provides support for anonymous functions, the so-called anonymous function is simply a single line of code that can be implemented, such as what we have previously said about circular area functions, which can be defined by anonymous functions.

1 Lambda r:3.14 * R * r2print#  call

Execution results

50.24

Description: R is equivalent to the parameters of an anonymous function, of course, can have more than one parameter, do not write return, the expression is the result of the return.

The advantage of using anonymous functions is that the question function has no name, does not worry about the function name conflict, and the anonymous function is also a function object, you can assign the anonymous function to a variable, and then use the variable to invoke the function.

5. Return statement about function

1) function can have no return statement, no return statement returned by default is None

2) The return statement is a bit like a looping break, and when the function executes to the return statement, it will not continue to execute, directly out of the function, for example

1 def Foo6 (): 2     Print ('start') 3     return None 4     Print ('end') 5 6 Print (Foo6 ())

Execution results

Startnone

Description: You can see that print (' end ') behind the return statement is not executed at all.

3) returns can return multiple values, accept the received can be accepted using two variables, or you can receive a variable

1 defFoo7 ():2     return123,'ABC'3 4Res1, Res2 =Foo7 ()5 Print('res1:', Res1)6 Print('Res2:', Res2)7 8res =Foo7 ()9 Print('Res:', res)

Execution results

res1:123res2:abcres: ('abc')

Note: You can return multiple values is to return a meta-ancestor, using two variables to receive the time back to the elements of the tuple and the variable one by one is assigned to a number of variables, with a variable received when the received

6. Tips on the transfer of variable parameters and keyword parameters

We already know that variable parameters and keyword parameters will be passed the parameters of the assembly Cheng Yuanju and dictionaries, then we can also directly pass the Ganso, lists and dictionaries directly to the function as parameters, passing the time list and Ganso to the variable name to add a *, the dictionary before adding two * *, Otherwise, the function will treat them as a normal parameter pass.

1 def Foo8 (*args, * *Kwargs):2     print(args)3     print( Kwargs)45Foo8 (Li, dic)6 Foo8 (*li, **dic)

Execution results

([1, 2, 3], {'K1'K2': 2#  You can see that two parameters have been received by the variable parameter, the keyword parameter is nothing (1, 2, 3) {'K1'K2  ': 2}

My Python growth path---the third day---python Foundation---January 16, 2016 (haze)

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.