"Basic Python Tutorial" reading notes the sixth chapter abstract function parameters

Source: Internet
Author: User

6.1 Creating a function

A function can be called (possibly containing a parameter, that is, a value placed in parentheses), which performs some behavior and returns a value. In general, the built-in callable function can be used to determine whether a function can be called:

>>> x=1

>>> y=math.sqrt

>>> Callable (x)

False

>>> Callable (Y)

True

Define a function with a def statement:

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

To add a document string to a function:

>>> def Square (x):

' Calculates the square of the number X '

Return x*x

The document string can be visited as follows:

>>> square.__doc__

' Calculates the square of the number X '

By using help in the interactive interpreter, you can get 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

Assigning a new value to a parameter within 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 Collect parameters:

The asterisk before the parameter places all values in the same tuple.

>>> def print_params (*params):

Print params

>>> print_params (' testing ')

(' testing ',)

>>> (Print_params)

(1, 2, 3)

Joint Common parameters

>>> defprint_params_2 (title,*params):

Print title

Print params

>>>print_params_2 (' params: ')

Params:

(1, 2, 3)

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

>>> print_params_2 (' Nothing: ')

Nothing

()

Cannot handle keyword parameters:

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

Traceback (most recent):

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

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

Can handle the "collect" operation of the keyword parameter:

>>> def Print_params_3 (**params):

.. print params

...

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

{' Y ': 2, ' X ': 1, ' Z ': 3} #返回的是字典而不是元组

Put together with:

>>> 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 3

()

{}

Implement multiple names to store at the same time:

>>> 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.3 reversal Process

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

>>> (params=)

>>> Add (*params)

3

Working with Dictionaries:

>>> 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 (allowing the use of an indefinite number of arguments) or calling ("splitting" a dictionary or sequence).

6.3 Scopes

Outside the global scope, each function call creates a new scope:

>>> def foo ():

... x=42

...

>>> x=1

>>> foo ()

>>> x

1

The assignment statement x=42 only works in the internal scope (local namespace), so it does not affect the X in the outer (global) scope. Variables within a function are called local variables (the local variable, which is the opposite of global variables). Parameters work like local variables, so it is not a problem to use the name of the global variable as the parameter name.

To access global variables inside a function:

>>> def combine (parameter):p rintparameter+external

>>> external= ' Berry '

>>> combine (' shrub ')

Shrubberry

6.4 Recursion

A useful recursive function consists of the following parts:

When a function returns a value directly, there is a basic instance (least possible problem), a recursive instance, including one or more recursive invocations of the smallest number of problems.

6.4.12 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 of 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,...]) : Apply a function to each element in a sequence

Filter (func. Seq): Returns the list of elements whose function is true

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

SUM (SEQ): Returns all the elements in the SEQ and

Apply (Func[,args[,kwargs]]): Call function, can provide parameters

"Basic Python Tutorial" reading notes the sixth chapter abstract function 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.