Home Backend Development Python Tutorial Detailed description of functions in python

Detailed description of functions in python

Mar 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]
Copy after login

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
Copy after login

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)
Copy after login

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.'
Copy after login

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.
Copy after login

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'
Copy after login

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']
Copy after login

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!
Copy after login

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)
Copy after login

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
()
{}
Copy after login

## 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'])
Copy after login

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
Copy after login

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)
Copy after login

Modify global variables

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

    
>>> f()
>>> x
>>> f()
>>> x
Copy after login

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)
Copy after login

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)
Copy after login

>>> def power(x,n):
    if n==0:
        return 1
    else:
        return x*power(x,n-1)

    
>>> power(2,3)
Copy after login


## 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)
Copy after login

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]
Copy after login

>>> 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;]
Copy after login

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]
Copy after login

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)
Copy after login

>>> 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;]
Copy after login

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
Copy after login

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

Statement of this Website
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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Introduction to Python functions: Usage and examples of abs function Introduction to Python functions: Usage and examples of abs function Nov 03, 2023 pm 12:05 PM

Introduction to Python functions: usage and examples of the abs function 1. Introduction to the usage of the abs function In Python, the abs function is a built-in function used to calculate the absolute value of a given value. It can accept a numeric argument and return the absolute value of that number. The basic syntax of the abs function is as follows: abs(x) where x is the numerical parameter to calculate the absolute value, which can be an integer or a floating point number. 2. Examples of abs function Below we will show the usage of abs function through some specific examples: Example 1: Calculation

Introduction to Python functions: Usage and examples of isinstance function Introduction to Python functions: Usage and examples of isinstance function Nov 04, 2023 pm 03:15 PM

Introduction to Python functions: Usage and examples of the isinstance function Python is a powerful programming language that provides many built-in functions to make programming more convenient and efficient. One of the very useful built-in functions is the isinstance() function. This article will introduce the usage and examples of the isinstance function and provide specific code examples. The isinstance() function is used to determine whether an object is an instance of a specified class or type. The syntax of this function is as follows

How to fix hardcoded errors in Python's functions? How to fix hardcoded errors in Python's functions? Jun 25, 2023 pm 08:15 PM

With the widespread use of the Python programming language, developers often encounter the problem of "hard-coded errors" in the process of writing programs. The so-called "hard coding error" refers to writing specific numerical values, strings and other data directly into the code instead of defining them as constants or variables. This approach has many problems, such as low readability, difficulty in maintaining, modifying and testing, and it also increases the possibility of errors. This article discusses how to solve the problem of hard-coded errors in Python functions. 1. What is hard

Introduction to Python functions: functions and examples of filter functions Introduction to Python functions: functions and examples of filter functions Nov 04, 2023 am 10:13 AM

Introduction to Python functions: The role and examples of the filter function Python is a powerful programming language that provides many built-in functions, one of which is the filter function. The filter function is used to filter the elements in the list and return a new list composed of elements that meet the specified conditions. In this article, we will introduce what the filter function does and provide some examples to help readers understand its usage and potential. The syntax of the filter function is as follows: filter(function

Introduction to Python functions: usage and examples of dir function Introduction to Python functions: usage and examples of dir function Nov 03, 2023 pm 01:28 PM

Introduction to Python functions: Usage and examples of dir function Python is an open source, high-level, interpreted programming language. It can be used to develop various types of applications, including web applications, desktop applications, games, etc. Python provides a large number of built-in functions and modules that can help programmers write efficient Python code quickly. Among them, the dir function is a very useful built-in function, which can help programmers view the properties and methods in objects, modules or classes.

Introduction to Python functions: functions and usage examples of globals functions Introduction to Python functions: functions and usage examples of globals functions Nov 04, 2023 pm 02:58 PM

Introduction to Python functions: functions and usage examples of the globals function Python is a powerful programming language that provides many built-in functions, among which the globals() function is one of them. This article will introduce the functions and usage examples of the globals() function, with specific code examples. 1. Functions of the globals function The globals() function is a built-in function that returns a dictionary of global variables of the current module. It returns a dictionary containing global variables, where

Introduction to Python functions: introduction and examples of range function Introduction to Python functions: introduction and examples of range function Nov 04, 2023 am 10:10 AM

Introduction to Python functions: Introduction and examples of range functions Python is a high-level programming language widely used in various fields. It is easy to learn and has a rich built-in function library. Among them, the range function is one of the commonly used built-in functions in Python. This article will introduce the function and usage of the range function in detail, and demonstrate its specific application through examples. The range function is a function used to generate an integer sequence. It accepts three parameters, which are the starting value (

How to resolve unsafe concurrency errors in Python functions? How to resolve unsafe concurrency errors in Python functions? Jun 24, 2023 pm 12:37 PM

Python is a popular high-level programming language with simple and easy-to-understand syntax, rich standard library and open source community support. It also supports multiple programming paradigms, such as object-oriented programming, functional programming, etc. In particular, Python is widely used in data processing, machine learning, scientific computing and other fields. However, Python also has some problems in multi-threaded or multi-process programming. One of them is concurrency insecurity. This article will introduce how to solve concurrency concerns in Python functions from the following aspects:

See all articles