The definition and use of Python functions

Source: Internet
Author: User
Tags iterable mathematical functions

I. Definition and creation of functions

function is Python The basic program structure provided for maximum reuse of code and minimization of code redundancy, which enables programmers to

Complex systems are decomposed into manageable parts. in the Python You can create four types of function:

Global functions: definition in templates
Local functions: nesting in other functions
Lambda Functions: also known as anonymous functions, expressions
Method: a function that is associated with a specific data type and can only be used with a data type association
    • Defining function syntax

def functionname (parameters):     suitereturn  value 

 def is an executable statement, So you can appear anywhere you can use a statement, or even nested in other statements, such as if Span class= "fontstyle0" >while def Creates an object and assigns it to a variable name ( The function name return none returne The function of the statement automatically returns none def After the statement is run, you can call it in the program by appending parentheses after the Function.

In [2]: def make_a_sound (): ...: print (' quack ') ...: in [3]: make_a_sound () quackin [4]: a=make_a_sound () Quacki n [5]: type (a) out[5]: nonetype

Above is a simplest parameterless function, which is called after Python executes the Function's internal Code. This function prints out a word, because the return value is not set, so the default is Nonetype.

    • Parameter Passing form

When a defined function has parameters, there are two forms of parameter passing.

Positional parameters: left-to-right, incoming parameter values are copied in order at a time

Keyword arguments: match key names when calling parameters, no need to worry about the position of the parameters when the function is defined

When mixed in the above two ways: write all positional parameters first, then all the keyword parameters
In [6]: def menu (wine,entree,dessert): ...: return{' wine ': wine, ' entree ': entree, ' dessert ':d essert} ...: in [7]: Menu (' Chardonnay ', ' chicken ', ' cake ') #依次传递参数, positional parameters out[7]: {' dessert ': ' cake ', ' entree ': ' chicken ', ' wine ': ' chard Onnay '}in [8]: menu (entree= ' beef ', dessert= ' bagel ', wine= ' Bordeaux ') #按关键字传递参数Out [8]: {' dessert ': ' bagel ', ' entree ': ' Beef ', ' wine ': ' Bordeaux '}

When you define a function, you can set a default parameter value for the parameter, which is used when the calling function does not specify a parameter Value. Parameters with no default values defined on the left, with default values on the Right.

In [9]: def menu (wine,entree,dessert= ' pudding '): ...: return{' wine ': wine, ' entree ': entree, ' dessert ':d essert} ...: In []: menu (' Chardonnay ', ' chicken ') out[10]: {' dessert ': ' pudding ', ' entree ': ' chicken ', ' wine ': ' Chardonnay '}

When defining a function that cannot determine the exact number of arguments, you can use variable parameters to collect the parameters, which are in two forms: one is to collect positional parameters and the other is to collect the keyword Parameters.

  defining functions using *   when defining functions use **:   collect keyword parameters   ( dictionary )
in [12]: def print_args (*args):       #使用 * Collect position parameters     ...:     print (' positional argument  tuple: ', Args)     ...:     in [13]: print_args () positional argument tuple:  () In [14]: print_args (1,2,3,4,5,6, ' 12131 ', ' ABCD ') positional argument tuple:  (1, 2, 3, 4, 5, 6,  ' 12131 ',  ' ABCD ') In [15]: def print_kwargs (**args):   #使用 * * Collect keyword Parameters     ...:      print (' keyword arguments: ', Args)     ...:      in [16]: print_kwargs (wine= ' merlot ', entree= ' mutton ') keyword arguments: {' wine ' :  ' Merlot ',  ' entree ':  ' mutton '} 
    • function scope

Python creating, changing, or locating a variable name is done in the namespace, where the value of the variable name is assigned determines the scope it can be accessed, the function defines the local scope, and the module defines the global Scope.
Each module is a global scope, so the scope of the global scope is limited to a single program File. each call to the program creates a new local scope, and the assigned variable is a local variable unless it is declared as a global variable. all variable names can be summarized as local, global, or built-in ( provided by the __builtin__ module ).

The variable name reference is divided into three functions: first local variable, then global variable, and last built-in Variable.

In [17]: animal= ' Fruitbat '       #定义全局变量In  [18]: def print_ Global ():     ...:     print (' inside print_global: ', animal)    #调用全局变量     ...:     in [20]: print_global () Inside print_global: fruitbatin [21]: def print_global ():    # When the function wants to change the global variable, the execution function will error     ...:     print (' inside print_global: ' , Animal)     ...:     animal= ' wombat '     ..:      print (' after the change: ', animal)     ...:      in [22]: print_global ()----------------------------------------------------- ----------------------unboundlocalerror                          traceback  (most recent call last) < Ipython-input-22-e3810348dd19> in <module> ()----> 1 print_global () < Ipython-input-21-906f76821837> in print_global ()       1 def  print_global ():----> 2     print (' inside print_global: ', animal)       3     animal= ' Wombat '        4     print (' after the change: ', animal)        5 UnboundLocalError: local variable  ' Animal '  referenced before  Assignmentin [27]: def print_global ():    #在函数内部声明全局变量, Then change the function can execute      ...:     global animal    ...:      print (' Inside priNt_global: ', animal)     ...:     animal= ' wombat '      ...:     print (' after the change: ', animal)      :         ...:          ...:     in [28]: print_global () inside print_global:  Wolfafter the change: wombat
    • Lambda () function

In python, a lambda function is an anonymous function that uses a statement expression, which can be used instead of a small function.

Syntax:Lambda args:expression

args: comma-separated List of parameters

expression: used to args expressions for each parameter in

Lambda the code defined by the statement must be a valid expression, and a multi-conditional statement cannot occur ( can use if 's ternary expression ) and other non-

An expression statement, such as for and the while and so on; Lambda The primary purpose of this is to specify a short callback letter number; Lambda will return a function without

is to assign a function to a variable.

It is important to note thatLambda is an expression, not a statement;Lambda is a single expression, not a block of code Def Statement Creation

The function

lambda lambda

in [29]: f=lambda x,y,z:x+y+z    # Summing     ...:     ...:     in using lambda anonymous functions  [30]: f (4,5,6) out[30]: 15in [31]: f=lambda x,y,z=10:x+y+z     ...:     ...:     ...:     in  [32]: f (3,7) out[32]: 20in [33]: stairs=[' thus ', ' Meow ', ' thud ', ' hiss ']in [34]:  f=lambda word: word.capitalize ()  + '! '    #创建lambda函数将字符串大写In  [37]: for i in stairs:      ...:      print (f (I))     ...:          ...:     thus! meow! thud! Hiss! 
    • Function-type programming

Also known as functional programming, is a programming paradigm; he calculates computer operations as mathematical functions and avoids state and variable

the most important foundation of a functional programming language is LAMDBA calculus, and Lambda the function of the calculation can accept functions as inputs and outputs.

Out Python supports limited functional programming:

Filter (function or None, Iterable) Call a Boolean function to iterate through the elements in each iterable and return a sequence of elements that enable the function return value to be True.
Map (func, *iterables) Sets the function func to each element of the sequence, and provides the return value with a list, if function is none,func as an identity function, returns a list of n tuples containing the set of elements in each sequence.

Reduce (func,seq[,init])

(discarded in Python3)

The elements of the two-tuple-scoped seq sequence, each carrying a pair (previous results and the next sequence element), continuously effect the existing result and the next value on the resulting subsequent result, and finally reduce the sequence to a single return value; The first comparison will be the Init and the first sequence element instead of the two header elements of the Sequence.

650) this.width=650; "src=" https://s4.51cto.com/wyfs02/M01/8F/5A/wKiom1jbghGxy50ZAADGp4re_rs512.png-wh_500x0-wm_ 3-wmp_4-s_2431335888.png "title=" qq20170329173313.png "alt=" wkiom1jbghgxy50zaadgp4re_rs512.png-wh_50 "/>

In [all]: li=[x for x in Range]in [max]: liout[43]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]in []: new_list=map (lambda a:a+10,l  I) #使用map函数对li列表中没个元素加10In [new_listout[45]: <map at 0x7fd595189828>in []: list (new_list) out[46]: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

650) this.width=650; "src=" https://s4.51cto.com/wyfs02/M01/8F/58/wKioL1jbghHgS50aAACjh6FJkXY033.png-wh_500x0-wm_ 3-wmp_4-s_2208837606.png "title=" qq20170329173323.png "alt=" wkiol1jbghhgs50aaacjh6fjkxy033.png-wh_50 "/>

In []: new_list2=filter (lambda arg:arg>5,li) #选出列表li中所有大于5的元素In [further]: list (new_list2) out[49]: [6, 7, 8, 9]
    • Design Specifications for functions

Coupling:

(1) accept input through parameters, and pass return generate output to ensure the independence of the function;

(2) minimizing the use of global variables for inter-function communication;

(3) do not modify the parameters of the mutable type in the function;

(4) Avoid directly changing the variables defined in another module;

Polymerization:

Each function should have a single, unified target, and each function should have a relatively simple function.

This article is from the "wind and drift" blog, Please be sure to keep this source http://yinsuifeng.blog.51cto.com/10173491/1911497

The definition and use of Python functions

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.