Python Learning Notes (4th lesson)

Source: Internet
Author: User

This section will learn how to define functions in Python, invoke functions, and learn the use of anonymous functions

1. Defining functions

In Python, define the function with the keyword Def, as shown in the following example, Testfun is the letter name

Def testfun ():

print "Hello World"

2. Function parameters

A function can have 0 or more formal parameters:

def testadd (x, y):

Print X+y

The formal parameter value of the function can be initialized, using the parameters of the initial value, which can be called without specifying the parameter.

def testsum (z,x=1,y=0):

Print X+y+z

Call Function:

Testsum (3) # will print out: 4

Testsum (10,y=1) # will print out: 12

Testsum (y=1,x=2,z=10) #将打印出: 13

Note: When defining a function, a formal parameter without initialization must precede the initialization form parameter, or an error will be

When you call a function, you must specify an uninitialized parameter, and the order of the parameters is consistent with the order of the parameters defined by the function (unless the parameter name is specified when called)

3. function return value

A Python function can return a function value through a return statement, and if there is nothing after the return statement or RETURN statement, the function returns: None

def testsub (x, y):

return x-y

Call Function:

X=testsub (10,2)
Print x #将打印出: 8

4. Function parameters in the form of dictionaries and tuples

The number of formal parameters of a Python function is sometimes uncertain, and we can use the formal parameters of *args or **args. *args receives the parameter as a tuple, and **args receives the parameter as a dictionary, and when both are present, the *args must be defined in front of **args when the function is defined

Dictionary parameter (**args) Example:

def testdict (a,**b):

print ' A is: ', a

print ' B is: ', b

Call function Method One:

tict={' x ': 1, ' Y ': 2, ' Z ': 3}
Testdict (10,**tict)

Call function Method Two:

Testdict (10,x=1,y=2,z=3)

Output Result:

>>>
A is:10
B is: {' Y ': 2, ' X ': 1, ' Z ': 3}

Example of a tuple parameter (*args):

def testtuple (a,*b):

print ' A is: ', a

Print B

Call function Method One:

tup= (' A ', +, ' B ')
Testtuple (1,*tup)

Call function Method Two:

Testtuple (1, ' A ', and, ' B ')

Output Result:

>>>

A is:1

(' A ', 1, 2, ' B ')

5. Anonymous functions

Python can use the keyword lambda to define an anonymous function, and when an object of a function type is needed, an anonymous function can be created to implement

def testlambda (x):

Return Lambda X:x+y #这里将返回一个函数对象

Function call:

F=testlambda (#创建了一个函数对象): F
Print f (5) #将会打印出: 15

6. Key Notes

When a function with an initialization parameter is called multiple times, the parameter is initialized only once on the first call. This makes it possible that when a formal parameter is a mutable object, such as a list, dictionary, or instance of a class, the result may not be the same as we expected:

def testparam (x=[]):

X.append (10)

Print X

Call the function multiple times (perhaps we want the result of calling the function to be: Print out the list [10]):

Testparam ()
Testparam ()
Testparam ()
Testparam ()

Actual output results:

>>>
[10]
[10, 10]
[10, 10, 10]
[10, 10, 10, 10]

What happens when the formal parameter is an immutable object? Let's look at another example:

def testparam (x=2):

X=x+2

Print X

Call Function:

Testparam ()
Testparam ()
Testparam ()
Testparam ()

Actual output results:

>>>
4
4
4
4

Note:

In Python, everything is object.

There is no so-called call-to-value in Python, and all that is passed is a reference to the object, or it can be thought of as a pass-through.

Immutable objects (immutable): int, string, float, (numeric number), tuple (tuple)

mutable objects (mutable): Word-typical (dictionary), List-type, class-instance

Python Learning Notes (4th lesson)

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.