Chapter 6 abstract function parameters, Python Functions

Source: Internet
Author: User

Chapter 6 abstract function parameters, Python Functions

6.1 create a function

A function can be called (which may contain parameters, that is, the values placed in parentheses). It performs a certain action and returns a value. In general, the built-in callable function can be used to determine whether the function is callable:

>>> x=1

>>> y=math.sqrt

>>> callable(x)

False

>>> callable(y)

True

Def statement for defining functions:

def fib(num):
result=[0,1]
for i in range(num-2):
result.append(result[-2]+result[-1])
return result

6.1.1 record Function

Add a document string to the function:

>>> def square(x):

'calculates the square of the number x'

return x*x

The document string can be accessed as follows:

>>> square.__doc__

'calculates the square of the number x'

Use help in the interactive interpreter to obtain information about the function, including its document string:

>>> help(square)

Help on function square:

 

square(x)

calculates thesquare of the number x

6.2.1 Parameters

Adding a new value to a parameter in a function does not change the value of any external variable:

>>> def try_to_change(n):

n='Mr.gumby'

>>> name='Mrs.entity'

>>> try_to_change(name)

>>> name

'Mrs.entity'

Default Value of the parameter:

>>> def hello(greeting='hello',name='world'):

print '%s,%s!'%(greeting,name)

>>> hello()

hello,world!

>>> hello('greeting')

greeting,world!

>>> hello('greeting','universe')

greeting,universe!

6.2.2 collection parameters:

The asterisks before the parameter place all values in the same tuples.

>>> def print_params(*params):

print params

>>> print_params('testing')

('testing',)

>>> print_params(1,2,3)

(1, 2, 3)

Join common parameters

>>> defprint_params_2(title,*params):

print title

print params

>>>print_params_2('params:',1,2,3)

params:

(1, 2, 3)

If no element is provided for collection, params is an empty ancestor.

>>> print_params_2('nothing:')

nothing:

()

Keyword parameters cannot be processed:

>>>print_params_2('hmm...',something=42)

Traceback (most recent call last):

File "<input>", line 1, in <module>

TypeError: print_params_2() got anunexpected keyword argument 'something'

"Collection" operations that can process keyword parameters:

>>> def print_params_3(**params):

... print params

...

>>> print_params_3(x=1,y=2,z=3)

{'Y': 2, 'x': 1, 'z': 3} # The returned dictionary is not a tuples.

Used Together:

>>> defprint_params_4(x,y,z=3,*pospar,**keypar):

... print x,y,z

... print pospar

... print keypar

...

>>>print_params_4(1,2,3,5,6,7,foo=1,bar=2)

1 2 3

(5, 6, 7)

{'foo': 1, 'bar': 2}

>>> print_params_4(1,2)

1 2 3

()

{}

Multiple names can be stored simultaneously:

>>> def init(data):

data['first']={}

data['middle']={}

data['last']={}

def lookup(data,label,name):

return data[label].get(name)

def store(data,*full_names):

for full_name in full_names:

names=full_name.split()

if len(names)==2:names.insert(1,'')

labels='first','middle','last'

for label,name in zip(labels,names):

people=lookup(data,label,name)

if people:

people.append(full_name)

else:

data[label][name]=[full_name]

>>> store(d,'luke skywalker','anakin skywalker')

>>> lookup(d,'last','skywalker')

['luke skywalker', 'anak in skywalker']

6.2.3Reversal Process

>>> def add(x,y):return x+y

>>> params=(1,2)

>>> add(*params)

3

Processing dictionary:

>>> defhello_3(greeting='Hello',name='world'):

... print '%s,%s!'%(greeting,name)

...

>>> params={'name':'sirrobin','greeting':'well met'}

>>> hello_3(**params)

well met,sir robin!

Asterisks are only useful when defining functions (parameters with an indefinite number are allowed) or calling ("split" dictionary or sequence.

6.3 Scope

Outside the global scope, each function call will create a new scope:

>>> def foo():

... x=42

...

>>> x=1

>>> foo()

>>> x

1

The value assignment statement x = 42 takes effect only in the internal scope (local namespace), so it does not affect x in the external (global) scope. A variable in a function is called a local variable, which is the opposite of a global variable ). The working principle of a parameter is similar to that of a local variable. Therefore, it is no problem to use the name of a global variable as the parameter name.

To access global variables within the function:

>>> def combine(parameter):printparameter+external

>>> external='berry'

>>> combine('shrub')

shrubberry

6.4 Recursion

A useful recursive function contains the following parts:

When a function returns a value directly, there are basic instances (least likelihood problem) and recursive instances, including recursive calls of the least part of one or more problems.

6.4.1 two classics: factorial and power

>>> def factorial(n):

... result=n

... for i in range(1,n):

... result*=i

... return result

...

>>> factorial(5)

120

Or:

>>> def factorial(n):

... if n==1:

... return 1

... else:

... return n*factorial(n-1)

...

>>> factorial(5)

120

Power calculation:

>>> Def power (x, n ):

... Result = 1

... For I in range (n ):

... Result * = x

... Return result

...

>>> Power (2, 3)

8

Or:

>>> def power(x,n):

... if n==0:

... return 1

... else:

... return x*power(x,n-1)

...

>>> power(2,3)

8

New functions in this chapter:

Map (func, seq [, seq,...]): applies a function to each element in the sequence.

Filter (func. seq): returns the list of elements whose functions are real elements.

Reduce (func, seq [, initial]): equivalent to func (seq [0], seq [1]),...)

Sum (seq): returns the sum of all elements in seq.

Apply (func [, args [, kwargs]): Call a function and provide parameters

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.