search
HomeBackend DevelopmentPython TutorialDetailed description of functions in python
Detailed description of functions in pythonMar 08, 2017 am 10:17 AM
python function

Fibonacci Sequence

>>> 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 Define function

>>> def hello(name):
    print "Hello"+name

    
>>> hello('world')
Helloworld

Use function to write Fibonacci sequence

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

        
>>> fibs(10)

Note: The return statement returns the value from the function

Function description: If you document the function so that others can understand it, you can add comments ( #beginning). Another way 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 get information about the function, including its documentation string

>>> help(square)
Help on function square in module __main__:

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

Assigning new values ​​to parameters within a function does not change the value of external variables:

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

    
>>> name='Mrs,Entity'
>>> try_to_change(name)
>>> name
'Mrs,Entity'

Strings (as well as numbers and tuples) It is immutable, that is, it cannot be modified. If the changeable data structure (list or dictionary) is modified, the parameters will be 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!

Collect parameters

Return tuple:

>>> def print_params(*params):
    print params

    
>>> print_params('Testing') #返回元组
('Testing',)
>>> print_params(1,2,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)

Return 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)
2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params_4(1,2)
2 3
()
{}

## Call tuple, dictionary

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

>>> params=(1,2)
>>> add(*params)
>>> 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'])

The asterisk is only useful when defining a function (allowing an indefinite number of parameters) or calling ("splitting" a dictionary or sequence)

>>> 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)
3 4 Hi Hello
>>> call_foo(*d,**f)
Calling foo!
3 4 Hi Hello

A few 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=&#39;king&#39;,name=&#39;Gumby&#39;)
Once upon a time,there was aking called Gumby.
>>> print story(name=&#39;Sir Robin&#39;,job=&#39;brave knight&#39;)
Once upon a time,there was abrave knight called Sir Robin.
>>> params={&#39;job&#39;:&#39;language&#39;,&#39;name&#39;:&#39;Python&#39;}
>>> print story(**params)
Once upon a time,there was alanguage called Python.
>>> del params[&#39;job&#39;]
>>> print story(job=&#39;store of genius&#39;,**params)
Once upon a time,there was astore of genius called Python.
>>> power(2,3)
>>> power(y=3,x=2)
>>> params=(5,)*2
>>> power(*params)
>>> power(3,3,&#39;Helld,world&#39;)
Received redundant parameters: (&#39;Helld,world&#39;,)
>>> 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)

Modify global variables

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

    
>>> f()
>>> x
>>> f()
>>> x

Nesting

>>> def multiplier(factor):
    def multiplyByFactor(number):
        return number*factor
    return multiplyByFactor

>>> double=multiplier(2)
>>> double(5)
>>> multiplier(2*5)
<function multiplyByFactor at 0x0000000002F8C6D8>
>>> multiplier(2)(5)

Recursive (call)

Factorial and power

>>> def factorial(n):
    if n==1:
        return 1
    else:
        return n*factorial(n-1)
    
>>> factorial(5)
>>> 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)


## 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)

map function

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

>>> map(str,range(10))
[&#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;]
>>> 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,[&#39;ASDF&#39;,&#39;jskk&#39;])
[&#39;Asdf&#39;, &#39;Jskk&#39;]

filter function

it Receives a function and a list (list). This function judges each element in turn and returns True or False. filter() automatically filters out elements that do not meet the conditions based on the judgment results and returns a new list composed of elements that meet the conditions.

>>> def is_not_empty(s):
    return s and len(s.strip())>0

>>> filter(is_not_empty,[None,&#39;dshk&#39;,&#39;  &#39;,&#39;sd&#39;])
[&#39;dshk&#39;, &#39;sd&#39;]
>>> def pfg(x):
    s=math.sqrt(x)
    if s%1==0:
        return x

>>> import math
>>> pfg(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 function

is also called an anonymous function, that is, the function has no specific name and is created with def The method is named

>>> def foo():return &#39;Begin&#39;

>>> lambda:&#39;begin&#39;
<function <lambda> at 0x0000000002ECC2E8>
>>> s=lambda:&#39;begin&#39;
>>> print s()
begin
>>> s= lambda x,y:x+y
>>> print s(1,2)
>>> def sum(x,y=6):return x+y

>>> sum2=lambda x,y=6:x+y
>>> sum2(4)

>>> 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(),[&#39;8ui&#39;,&#39;&j&#39;,&#39;lhg&#39;,&#39;)j&#39;])
[&#39;8ui&#39;, &#39;lhg&#39;]

reduce function

It receives a function and A list (list), the function must receive two parameters. This function calls each element of the list in turn and returns a new list composed of the result values

>>> reduce(lambda x,y:x*y,range(1,5))
24
>>> reduce(lambda x,y:x+y,[23,9,5,6],100) #初始值为100,依次相加列表中的值
143

For more detailed descriptions of functions in python, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python函数介绍:abs函数的用法和示例Python函数介绍:abs函数的用法和示例Nov 03, 2023 pm 12:05 PM

Python函数介绍:abs函数的用法和示例一、abs函数的用法介绍在Python中,abs函数是一个内置函数,用于计算给定数值的绝对值。它可以接受一个数字参数,并返回该数字的绝对值。abs函数的基本语法如下:abs(x)其中,x是要计算绝对值的数值参数,可以是整数或浮点数。二、abs函数的示例下面我们将通过一些具体的示例来展示abs函数的用法:示例1:计算

Python函数介绍:isinstance函数的用法和示例Python函数介绍:isinstance函数的用法和示例Nov 04, 2023 pm 03:15 PM

Python函数介绍:isinstance函数的用法和示例Python是一门功能强大的编程语言,提供了许多内置函数,使得编程变得更加方便和高效。其中一个非常有用的内置函数是isinstance()函数。本文将介绍isinstance函数的用法和示例,并提供具体的代码示例。isinstance()函数用于判断一个对象是否是指定的类或类型的实例。该函数的语法如下

如何解决Python的函数中的硬编码错误?如何解决Python的函数中的硬编码错误?Jun 25, 2023 pm 08:15 PM

随着Python编程语言的广泛应用,开发者们常常会在编写程序过程中遇到“硬编码错误”的问题。所谓“硬编码错误”,指的是将具体的数值、字符串等数据直接写入代码中,而不是将其定义为常量或变量。这一做法存在多方面的问题,比如可读性低,难维护、修改和测试,同时也会增加出错的可能性。本篇文章就如何解决Python函数中的硬编码错误这一问题进行探讨。一、什么是硬

Python函数介绍:dir函数的用法和示例Python函数介绍:dir函数的用法和示例Nov 03, 2023 pm 01:28 PM

Python函数介绍:dir函数的用法和示例Python是一种开源的、高级的、解释性的编程语言。它可用于开发各种类型的应用程序,包括Web应用程序、桌面应用程序和游戏等。Python提供了大量的内置函数和模块,这些函数和模块可以帮助程序员快速编写高效的Python代码。其中,dir函数是一个非常有用的内置函数,它可以帮助程序员查看对象、模块或类中的属性和方法

Python函数介绍:filter函数的作用和示例Python函数介绍:filter函数的作用和示例Nov 04, 2023 am 10:13 AM

Python函数介绍:filter函数的作用和示例Python是一种功能强大的编程语言,提供了许多内置的函数,其中之一就是filter函数。filter函数用于过滤列表中的元素,并返回满足指定条件的元素组成的新列表。在本文中,我们将介绍filter函数的作用,并提供一些示例来帮助读者理解其用法和潜力。filter函数的语法如下:filter(function

Python函数介绍:range函数的介绍及示例Python函数介绍:range函数的介绍及示例Nov 04, 2023 am 10:10 AM

Python函数介绍:range函数的介绍及示例Python是一种广泛应用于各种领域的高级编程语言,它具有简单易学的特点,并且有着丰富的内置函数库。其中,range函数是Python中常用的一个内置函数之一。本文将详细介绍range函数的功能以及使用方法,并通过实例来演示其具体的应用。range函数是用来生成一个整数序列的函数,它接受三个参数,分别是起始值(

如何解决Python的函数中的并发不安全错误?如何解决Python的函数中的并发不安全错误?Jun 24, 2023 pm 12:37 PM

Python是一门流行的高级编程语言,它具有简单易懂的语法、丰富的标准库和开源社区的支持,而且还支持多种编程范式,例如面向对象编程、函数式编程等。尤其是Python在数据处理、机器学习、科学计算等领域有着广泛的应用。然而,在多线程或多进程编程中,Python也存在一些问题。其中之一就是并发不安全。本文将从以下几个方面介绍如何解决Python的函数中的并发不安

Python函数介绍:globals函数的功能和使用示例Python函数介绍:globals函数的功能和使用示例Nov 04, 2023 pm 02:58 PM

Python函数介绍:globals函数的功能和使用示例Python是一种功能强大的编程语言,提供了许多内置函数,其中globals()函数就是其中之一。本文将介绍globals()函数的功能和使用示例,并附带具体的代码示例。一、globals函数的功能globals()函数是一个内置函数,用于返回当前模块的全局变量的字典。它返回一个包含全局变量的字典,其中

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)