Functions in Python3

Python function

A function is an organized, reusable piece of code that implements a single, or related function.

Functions can improve application modularity and code reuse. Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.

1. Definition of the function:

You can define a function that does what you want, the following are simple rules:

  • A function code block begins with the  def  keyword, followed by the function identifier name and parentheses () .
  • Any incoming parameters and arguments must be enclosed in parentheses. The parentheses can be used to define parameters.
  • The first line of statements in a function can optionally use a docstring—for function descriptions.
  • Function content starts with a colon and is indented.
  • pass  keyword, which means do nothing
  • exit(num)    forcibly exit (num: is a number, displayed as an exit code)
  • return [expression]  Ends the function, optionally returning a value to the caller. return without an expression is equivalent to returning None.

grammar

def functionname( parameters ):
   function_suite
   return [expression]

By default, parameter values ​​and parameter names are matched in the order defined in the function declaration.

Example 1:

def add(x, y):
print(“x = {0}”.format(x))
print(“x = {0}”.format(x))
print(“x  + y  = {0}”.format(x+y))
return x+y

 Example 2:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/14 20:31
# @Author  : Feng Xiaoqing
# @File    : demo1.py
# @Function: -----------


def f(x,l=[]):
    for i in range(x):
        l.append(i*i)
    print(l)

# f(2) = f(2, l=[])

f(2)
# 结果:[0, 1]

f(3,[3,2,1])
# 结果: [3, 2, 1, 0, 1, 4]

f(x=3, l=[])
# 结果: [0, 1, 4]

operation result:

[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 4]

 

2. Function call

Defining a function only gives the function a name, specifies the parameters contained in the function, and the code block structure.

Once the basic structure of this function is complete, you can execute it via another function call or directly from the Python prompt.

The following example calls the add() function:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/15 21:01
# @Author  : Feng Xiaoqing
# @File    : demo2.py
# @Function: -----------

# 自定义加法函数add()
def add(x,y):
    print("{0} + {1} = {2}".format(x,y,x+y))
    return
    print("finished")   #在return后不会执行这条语句


# 调用函数,计算2+3的得数
add(2,3)

operation result:

2 + 3 = 5

 

3. Parameters of the function

Formal and actual parameters

    When defining a function, the variable name in parentheses after the function name is called a formal parameter, or "formal parameter"

    When calling a function, the variable name in parentheses after the function name is called the actual parameter, or "actual parameter"

       

 def fun(x,y):  //形参

    print(x + y)

    fun(1,2)     //实参

    3

    fun('a','b')

    ab

Function default parameters:

    Default parameter (default parameter)

def fun(x,y=100)    

  print x,y


#调用:

fun(1,2)

fun(1)

    definition:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def fun(x=2,y=3):

  print x+y

    

    transfer:

fun()
#结果:
5


fun(23)
#结果
26


fun(11,22)
#结果:
33

 

We often look at other people's code, often in the form of def(*args, **kwargs):

*args refers to: tuple (1, )
**kwargs refers to: dict {"k": "v"}

fun(*args, **keargs)
fun(1, 2, 3, 4, 5, a=10, b=40)

 

4. The return value of the function

Function return value:

When the function is called, it returns a specified value

Returns None by default after the function is called

return return value

The return value can be of any type

After return is executed, the function terminates

The difference between return and print

#!/usr/bin/env python
# -*- coding:utf-8 -*-
def fun():

  print 'hello world'

  return 'ok'

  print 123


fun()

#结果

hello world

123

None

 

5. Variables of a function

Local and global variables:

Any variable in Python has a specific scope

Variables defined in a function can generally only be used within the function. These variables that can only be used in a specific part of the program are called local variables

Variables defined at the top of a file can be called by any function in the file. These variables that can be used by the entire program are called global variables.

def fun():

   x=100

   print x

fun()

x = 100

    

def fun():

   global x   //声明

   x +=1

   print x

fun()

print x

   

 

The external variable is changed (x is changed from 100 to 101):

x = 100

def fun():

  global x

  x += 1

  print (x)

fun()

print (x)


#结果
101
101

 

Inner variables are also available outside:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/15 21:33
# @Author  : Feng Xiaoqing
# @File    : demo2.py
# @Function: -----------

x = 100

def fun():

    global x

    x +=1

    global y

    y = 1

    print(x)

fun()

print(x)

print(y)


#结果:
101
101
1

   

Variables in the statistical program, which returns a dictionary

#!/usr/bin/env python
# -*- coding:utf-8 -*-

x = 100
def fun():
    x = 1
    y = 1
    print(locals())

fun()
print (locals())

  result:

{'y': 1, 'x': 1}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x02FF6390>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/PycharmProjects/PythonLive/untitled/day07/demo2.py', '__cached__': None, 'x': 100, 'fun': <function fun at 0x052D2390>}

 

6. Anonymous functions

As the name implies, it is a function without a name, so why set up an anonymous function and what does it do?
A lambda function is a minimal function that quickly defines a single line and can be used anywhere a function is required

python uses lambdas to create anonymous functions.

  • lambda is just an expression, and the function body is much simpler than def.
  • The body of a lambda is an expression, not a block of code. Only limited logic can be encapsulated in lambda expressions.
  • A lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.
  • Although the lambda function looks like it can only write one line, it is not equivalent to the inline function of C or C++. The purpose of the latter is to call small functions without occupying the stack memory and thus increase the running efficiency.

grammar

The syntax of a lambda function consists of only one statement, as follows:

lambda [arg1 [,arg2,.....argn]]:expression

 Example:

Find the product of two numbers:

Conventional writing:

def fun(x,y)
  return x*y

The lambda version is written:

r = lambda x,y:x*y


7. Higher order functions

(1)map(f, list)

Returns a list of values ​​computed by f for each element

map()The function receives two parameters, one is a function and the other is a sequence. mapThe passed-in function is applied to each element of the sequence in turn, and the result is returned as a new list.

Example: Calculate the square of values ​​in a list

#!/usr/bin/env python
# -*- coding:utf-8 -*-

def f(x):
    return x*x

for i in map(f,[1,2,3,4,5,6,7]):
    print(i)

result:

1
4
9
16
25
36
49

 

(2) reduce(f,list) function (to find the sum of the numbers in the list)

reduce applies a function to a sequence [x1, x2, x3...]. This function must receive two parameters. Reduce continues the result and accumulates the next element of the sequence. The effect is:

Example: Calculate the sum of all numbers in a list

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from functools import reduce  #导入reduce函数

def f(x,y):
    return x+y
print(reduce(f,[1,2,3,4,5,6,7,8,9,10]))
print(reduce(f,range(1,101)))


#结果:
55
5050

 

(3) filter() function (filtering)

The filter function receives a function f and a list. The function of the function f is to judge each element and return True or False. According to the judgment result, filter() automatically filters out the elements that do not meet the conditions, and returns a list of elements that meet the requirements.

filter(lamdba x: x%2 ==1, [1, 2, 3, 4, 5])

Example: Counting the numbers less than 7 in a list

#!/usr/bin/env python
# -*- coding:utf-8 -*-

for i in filter(lambda x:x<7, [1, 2, 3, 4, 5,40,8]):
    print(i)


#结果:
1
2
3
4
5

 

(4) sorted() function (sorting)

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

# sorted(iterable, key, reverse)
# iterable an iterable object
# what to sort by key
# reverse bool type, if true is reverse order, default is false
# return value is a list

Example:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/15 22:47
# @Author  : Feng Xiaoqing
# @File    : demo3.py
# @Function: -----------


m = dict(a=1, c=10, b=20, d=15)
print(sorted(m.items(), key = lambda d:d[1],reverse = True)) #按value值倒序排列


#结果:
[('b', 20), ('d', 15), ('c', 10), ('a', 1)]

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324407433&siteId=291194637