Python abstract learning 7--

Grouping statements into a function, you can tell the computer how to complete the task, and only said once, rather than repeatedly convey detailed instructions to the computer.

Fibonacci numbers (one of several columns, where each number is the first two numbers and):

>>> fibs = [0,1]
>>> for i in range(10):
    fibs.append(fibs[-2]+fibs[-1])

    
>>> fibs
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Optimizing the code, it specifies the dynamic range:

>>> fibs = [0,1]
>>> num = input('enter:')
enter:10
>>> for i in range(int(num)-2):
    fibs.append(fibs[-2]+fibs[-1])

    
>>> fibs
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

If you do not read numbers from the user, but to get through the parameters, we can continue to optimize the code:

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

>>> fibs(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

def statement defined functions, return statement is used to return values ​​from functions. num is a parameter, you can call fibs many times elsewhere (), instead of every time the code is then knock again.

 

In addition to # comments, there are comments written in a way, it is to add a separate string. At the beginning of the string function called document string.

>>> def square(x):
    'Calculates the square of the number x.'
    return x * x

Square >>>. The __doc__ # access documentation string 
' Calculates The Number of The X Square. '

__doc__ is the property function.

Help >>> (Square)     # built-in functions can help obtain information about the function 
Help function ON Square in Module __main__ :

square(x)
    Calculates the square of the number x.

 

Change parameters

When the variable parameter is a data structure (list), to modify the parameters within the function, the function call on the outside.

>>> def change(n):
    n[0] = 'Mr.Gumby'

    
>>> names = ['Mrs.Entity','Mrs.Thing']
>>> change(names)
>>> names
['Mr.Gumby', 'Mrs.Thing']

Above chestnuts can also write:

Names = >>> [ ' Mrs.Entity ' , ' Mrs.Thing ' ]
 >>> n-names =       # pretend name passed as a parameter 
>>> n-[0] = ' Mr.Gumby '      # modify the list, this step above is carried out within the function 
>>> names
['Mr.Gumby', 'Mrs.Thing']    

When two variables assigned to the same list, these two variables will also point to the list. Want to avoid this result, you must create a copy of the list.

Names = >>> [ ' Mrs.Entity ' , ' Mrs.Thing ' ]
 >>> n-names = [:]     # When slicing operation sequence, the slice is a copy of the return. Now it contains names and n 2 are equal but different list. Here you can also create a copy with names.copy (). 
N->>> [0] = ' Mr.Gumby ' 
>>> names
['Mrs.Entity', 'Mrs.Thing']
>>> n
['Mr.Gumby', 'Mrs.Thing']

Sections parameters passed to the function, it will not affect:

>>> def change(n):
    n[0] = 'Mr.Gumby'

    
>>> names = ['Mrs.Entity','Mrs.Thing']
>>> change(names[:])
>>> names
['Mrs.Entity', 'Mrs.Thing']

 

Chestnuts: Suppose you are writing a program, it stores the name, and enable users to by name, middle name or last name to find someone.

Create a function to initialize data structures:

>>> def init(data):
    data['first'] = {}
    data['middle'] = {}
    data['last'] = {}

    
Storage = >>> {}
 >>> the init (Storage)    # This function initializes assume responsibility, to improve the readability of the code. 
>>> Storage
{'first': {}, 'middle': {}, 'last': {}}

You then need a function to get the person's name:

>>> def lookup(data,label,name):
    return data[label].get(name)

To the art is then stored in the data structures:

>>> DEF Store (data, full_name):     # The data and parameters full_name provided to this function. 
    = full_name.split names ()    # create a list called names by splitting full_name. 
    IF len (names) == 2: names.insert (. 1, '' )   # If only the first and last names, no middle name, middle name will be set to an empty string 
    Labels = ' First ' , ' Middle ' , ' Last '     # the label stored in the tuple (and may be a list) 
    for name, label in ZIP (names, Labels):    # ZIP function label and name were combined, may label-name to perform some operation 
        people = Lookup (Data , label, name) 
        if people:
            people.append (full_name)   # The full_name insert a new list of 
        the else :
            data[label][name]=[full_name]

Now look at the operation:

>>> me = {}
>>> init(me)
>>> me
{'first': {}, 'middle': {}, 'last': {}}
>>> store(me,'Magnus Lie Hetland')
>>> me
{'first': {'Magnus': ['Magnus Lie Hetland']}, 'middle': {'Lie': ['Magnus Lie Hetland']}, 'last': {'Hetland': ['Magnus Lie Hetland']}}
>>> lookup(me,'middle','Lie')
['Magnus Lie Hetland']
>>> store(me,'Robin Hood')
>>> store(me,'Robin Locksley')
>>> store(me,'Mr. Gumby')
>>> lookup(me,'first','Robin')
['Robin Hood', 'Robin Locksley']
>>> lookup(me,'middle','')
['Robin Hood', 'Robin Locksley', 'Mr. Gumby']

 

Guess you like

Origin www.cnblogs.com/suancaipaofan/p/11074693.html