Introduction to functions in python and introduction to python Functions

Source: Internet
Author: User

Introduction to functions in python and introduction to python Functions

Fepolaxi Series

>>> fibs[0, 1]>>> n=input('How many Fibonacci numbers do your what?')How many Fibonacci numbers do your what?10>>> for n in range(n-2):    fibs.append(fibs[-2]+fibs[-1])    >>> fibs[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Note: The built-in callable function can be used to determine whether the function can be called.

Def Defined Functions

>>> def hello(name):    print "Hello"+name    >>> hello('world')Helloworld

Use functions to write the fepolaxi Series

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

Note: return statements return values from functions

Function Description: if you write a document to the function so that others can understand it, you can add a comment (starting ). Another method is to write the string directly.

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

The built-in help function can obtain information about the function, including its document string.

>>> help(square)Help on function square in module __main__:square(x)    Calculates the square of the number x.

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

>>> def try_to_change(n):    n='Mr,Gumby'    >>> name='Mrs,Entity'>>> try_to_change(name)>>> name'Mrs,Entity'

Strings (numbers and metadata) cannot be modified. If you modify the changeable data structure (list or dictionary), the parameter is modified.

>>> n=['Bob','Alen']>>> def change(m):    m[0]='Sandy'    >>> change(n[:])>>> n['Bob', 'Alen']>>> change(n)>>> n['Sandy', 'Alen']

Keyword parameters and default values

>>> def hello(name,greeting='Hello',punctuation='!'):    print '%s,%s%s' % (greeting,name,punctuation)    >>> hello(name='Nsds')Hello,Nsds!>>> hello(name='Nsds',greeting='Hi')Hi,Nsds!

Collection Parameters

Returned tuples:

>>> Def print_params (* params): print params >>> print_params ('testing') # returns the tuples ('testing ',) >>> print_params (, 3) (1, 2, 3) >>> def print_params_2 (title, * params): print title print params >>>> print_params_2 ('params: ', 1, 2, 3) params :( 1, 2, 3)

Back to Dictionary

>>> def print_params_3(**params):    print params    >>> print_params_3(x=1,y=2,z=3){'y': 2, 'x': 1, 'z': 3}>>> def print_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(){}

Call tuples and dictionaries

>>> def add(x,y):return x+y>>> params=(1,2)>>> add(*params)3>>> def with_stars(**kwds):    print kwds['name'],'is',kwds['age'],'years old']>>> def without_starts(kwds):    print kwds['name'],'is',kwds['age'],'years old'>>> args={'name':'Nsds','age':24}>>> with_stars(**args)Nsds is 24 years old>>> without_starts(args)Nsds is 24 years old>>> add(2,args['age'])26

Asterisks are only useful when defining functions (parameters with an indefinite number are allowed) or calling ("splitting" dictionaries or sequences ).

>>> def foo(x,y,z,m=0,n=0):    print x,y,z,m,n    >>> def call_foo(*args,**kwds):    print "Calling foo!"    foo(*args,**kwds)>>> d=(1,3,4)>>> f={'m':'Hi','n':'Hello'}>>> foo(*d,**f)1 3 4 Hi Hello>>> call_foo(*d,**f)Calling foo!1 3 4 Hi Hello

Examples

>>> def story(**kwds):    return 'Once upon a time,there was a' \           '%(job)s called %(name)s.' % kwds>>> def power(x,y,*others):    if others:        print 'Received redundant parameters:',others    return pow(x,y)>>> def interval(start,stop=None,step=1):    if stop is None:        start,stop=0,start  #start=0,stop=start    result=[]    i=start    while i<stop:        result.append(i)        i+=step    return result>>> print story(job='king',name='Gumby')Once upon a time,there was aking called Gumby.>>> print story(name='Sir Robin',job='brave knight')Once upon a time,there was abrave knight called Sir Robin.>>> params={'job':'language','name':'Python'}>>> print story(**params)Once upon a time,there was alanguage called Python.>>> del params['job']>>> print story(job='store of genius',**params)Once upon a time,there was astore of genius called Python.>>> power(2,3)8>>> power(y=3,x=2)8>>> params=(5,)*2>>> power(*params)3125>>> power(3,3,'Helld,world')Received redundant parameters: ('Helld,world',)27>>> interval(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> interval(1,5)[1, 2, 3, 4]>>> power(*interval(3,7))Received redundant parameters: (5, 6)81

Modify global variables

>>> def f():    global x    x=x+1    >>> f()>>> x2>>> f()>>> x3

Nesting

>>> def multiplier(factor):    def multiplyByFactor(number):        return number*factor    return multiplyByFactor>>> double=multiplier(2)>>> double(5)10>>> multiplier(2*5)<function multiplyByFactor at 0x0000000002F8C6D8>>>> multiplier(2)(5)10

Recursion (call)

Factorial and power

>>> def factorial(n):    if n==1:        return 1    else:        return n*factorial(n-1)    >>> factorial(5)120>>> range(3)[0, 1, 2]>>> def power(x,n):    result=1    for i in range(n):        result *= x    return result>>> power(5,3)
>>> def power(x,n):    if n==0:        return 1    else:        return x*power(x,n-1)    >>> power(2,3)8

Binary Search

>>> def search(s,n,min=0,max=0):    if max==0:        max=len(s)-1    if min==max:        assert n==s[max]        return max    else:        middle=(min+max)/2        if n>s[middle]:            return search(s,n,middle+1,max)        else:            return search(s,n,min,middle)        >>> search(seq,100)5

Map Functions

It receives a function and a list, and uses the function to function on each element of the list in turn to get a new list and return

>>> map(str,range(10))['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> def f(x): return x*x>>> print map(f,[1,2,3,4,5,6,7])[1, 4, 9, 16, 25, 36, 49]
>>> def format_name(s):    s1=s[0].upper()+s[1:].lower()    return s1>>> print map(format_name,['ASDF','jskk'])['Asdf', 'Jskk']

Filter Function

It receives a function and a list. This function judges each element in sequence and returns True or False. filter () automatically filters out non-conforming elements based on the judgment result, returns a new list composed of qualified elements.

>>> def is_not_empty(s):    return s and len(s.strip())>0>>> filter(is_not_empty,[None,'dshk','  ','sd'])['dshk', 'sd']>>> def pfg(x):    s=math.sqrt(x)    if s%1==0:        return x>>> import math>>> pfg(100)100>>> pfg(5)>>> filter(pfg,range(100))[1, 4, 9, 16, 25, 36, 49, 64, 81]>>> def is_sqr(x):    return math.sqrt(x)%1==0>>> is_sqr(100)True>>> filter(is_sqr,range(100))[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Lambda Functions

It is also called an anonymous function, that is, the function does not have a specific name, and the method created with def has a name.

>>> def foo():return 'Begin'>>> lambda:'begin'<function <lambda> at 0x0000000002ECC2E8>>>> s=lambda:'begin'>>> print s()begin>>> s= lambda x,y:x+y>>> print s(1,2)3>>> def sum(x,y=6):return x+y>>> sum2=lambda x,y=6:x+y>>> sum2(4)10
>>> filter(lambda x:x*x,range(1,5))[1, 2, 3, 4]>>> map(lambda x:x*x,range(1,5))[1, 4, 9, 16]>>> filter(lambda x:x.isalnum(),['8ui','&j','lhg',')j'])['8ui', 'lhg']

Reduce Function

It receives a function and a list. The function must receive two parameters. This function calls each element of the list in sequence and returns a new list composed of result values.

>>> Reduce (lambda x, y: x * y, range () 24 >>> reduce (lambda x, y: x + y, [,], 100) # The initial value is 100, and the values in the list are added in sequence to 143.

 

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.