Definition and use of python function

Definition and Creation of Functions

  Function is the basic program structure provided by Python to maximize code reuse and minimize code redundancy; it allows programmers to

Complex systems are decomposed into manageable components. Four functions can be created in Python:

Global functions: defined in templates
Local functions: nested in other functions
Lambda function: also known as anonymous function, expression
Method: Functions associated with a particular data type and can only be used with data type associations
  • Defining Functional Grammar

def functionName(parameters):
return value

 DEF is an executable statement, so it can appear anywhere you can use a statement, or even nested in other statements, such as if or while; def creates an object and assigns it to a variable name (function name); return is used to return the result object, which is optional; function without return statement is automatic Returns the none object; after the def statement runs, it can be invoked in parentheses after the function is passed in the program.

In [2]: def make_a_sound():
   ...:     print('quack')
In [3]: make_a_sound()
In [4]: a=make_a_sound()
In [5]: type(a)
Out[5]: NoneType

  The above is the simplest parametric-free function that python executes after calling. This function prints out a word and defaults to NoneType because the return value is not set.

  • Parametric Transfer Form

  When the defined function has parameters, there are two forms of parameter transfer.

  Location parameters: From left to right, the values of the incoming parameters are copied in sequence once. 

  Keyword parameters: When calling parameters, they are matched by key names, without concern for the position of parameters when defining functions.

  When mixing the above two ways, first write all the location parameters, then all the keyword parameters.
In [6]: def menu(wine,entree,dessert):     
   ...:     return{'wine':wine,'entree':entree,'dessert':dessert}
In [7]: menu('chardonnay','chicken','cake')      #Transfer parameters in turn, position parameters
Out[7]: {'dessert': 'cake', 'entree': 'chicken', 'wine': 'chardonnay'}
In [8]: menu(entree='beef',dessert='bagel',wine='bordeaux') #Pass parameters by keyword
Out[8]: {'dessert': 'bagel', 'entree': 'beef', 'wine': 'bordeaux'}

 Defining a function can set default parameter values for parameters, which are used when the calling function does not specify a parameter value. Parameters with no default value are defined on the left and parameters with default value are defined on the right.

In [9]: def menu(wine,entree,dessert='pudding'):
   ...:     return{'wine':wine,'entree':entree,'dessert':dessert}
In [10]: menu('chardonnay','chicken')
Out[10]: {'dessert': 'pudding', 'entree': 'chicken', 'wine': 'chardonnay'}

  When the defining function can not determine the specific number of parameters, variable parameters can be used to collect parameters. There are two forms of dynamic parameters: one is to collect location parameters, the other is to collect keyword parameters.

  Use *: Collect location parameters (tuples) when defining functions
  Use **: Collect keyword parameters (dictionary) when defining functions
In [12]: def print_args(*args):     #Use * to collect location 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):  #Use ** to collect keyword parameters
    ...:     print('Keyword arguments:',args)
In [16]: print_kwargs(wine='merlot',entree='mutton')
Keyword arguments: {'wine': 'merlot', 'entree': 'mutton'}
  • Functional scope

  Python creates, changes, or finds variable names in namespaces; where variable names are assigned in code determines the scope they can be accessed; functions define local scopes, and modules define global scopes.
  Each module is a global scope, so the scope of the global scope is limited to a single program file. Each call to a program creates a new local scope, and the assigned variables are local unless declared as global variables. All variable names can be summarized as local, global, or built-in (provided by the _builtin_ module).

Variable name reference can be divided into three functions: first local variable, then global variable, and finally built-in variable.

In [17]: animal='fruitbat'     #Define global variables
In [18]: def print_global():
    ...:     print('inside print_global:',animal)  #Calling global variables
In [20]: print_global()
inside print_global: fruitbat

In [21]: def print_global():   #When a function wants to change a global variable, the execution function will report an 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)
UnboundLocalError: local variable 'animal' referenced before assignment

In [27]: def print_global():   #Declare global variables inside a function, and then change the function to execute
    ...:     global animal
    ...:     print('inside print_global:',animal)
    ...:     animal='wombat'
    ...:     print('after the change:',animal)
In [28]: print_global()
inside print_global: wolf
after the change: wombat
  • lambda() function

  In python, lambda functions are anonymous functions of a statement expression, which can be used to replace small functions.

Grammar: lambda args: expression

  args: A comma-separated list of parameters

  expression: Expressions for parameters in args

  The code defined by the Lambda statement must be a legitimate expression, and no conditional statements (using if's ternary expression) or other non-conditional statements can occur.

Expressional statements, such as for and while; Lambda's primary use is to specify short callback functions; Lambda will return a function without

It assigns a function to a variable.

  Note that Lambda is an expression, not a statement; lambda is a single expression, not a code block Def statement.

The lambda expression directly returns the function Lambda, which also supports the use of default functions.

In [29]: f=lambda x,y,z:x+y+z    #Summation using lambda anonymous function
In [30]: f(4,5,6)
Out[30]: 15

In [31]: f=lambda x,y,z=10:x+y+z
In [32]: f(3,7)
Out[32]: 20

In [33]: stairs=['thus','meow','thud','hiss']
In [34]: f=lambda word: word.capitalize() +'!'  #Create lambda functions to capitalize strings
In [37]: for i in stairs: 
    ...:     print(f(i))
  • Functional Programming

  Also known as functional programming, it is a programming paradigm; it regards computer operations as mathematical function calculations, and avoids state and variability.

Data; The most important basis for functional programming languages is lamdba calculus, and functions of lambda calculus can accept functions as input inputs.

Out. python supports limited functional programming:

filter(function or None, iterable)Call a Boolean function to iterate through the elements in each iterable, returning a sequence of elements that make the function return true.
map(func, *iterables)The function func scopes each element of a given sequence and provides a return value with a list. If the function is none, func represents an identity function and returns a list of n tuples containing the set of elements in each sequence.


(discarded in Python 3)

A pair of elements in the seq sequence of binary function scope is carried each time (the previous result and the next sequence element). The existing result and the next value are applied to the subsequent result successively, and finally the sequence is reduced to a single return value. If the accident value is given, the first comparison will be init and A sequence element rather than two head elements of a sequence.

In [42]: li=[x for x in range(10) ]
In [43]: li
Out[43]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [44]: new_list=map(lambda a:a+10,li)    #Use map functions to add 10 to none of the elements in the li list
In [45]: new_list
Out[45]: <map at 0x7fd595189828>
In [46]: list(new_list)
Out[46]: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]


In [48]: new_list2=filter(lambda arg:arg>5,li) #Select all 5 elements in list li
In [49]: list(new_list2)
Out[49]: [6, 7, 8, 9]
  • Design Specification of Functions


  (1) Accepting input through parameters and generating output through return to ensure the independence of functions;

  (2) Minimizing the use of global variables for function-to-function communication;

  (3) Do not modify variable type parameters in functions;

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


  Each function should have a single, unified goal; each function should be relatively simple.

Keywords: Lambda Python Programming IPython

Added by sayedsohail on Sun, 14 Jul 2019 21:58:02 +0300