SoFunction
Updated on 2024-11-20

Python functions and python anonymous functions lambda in detail

1. python functions

1.1 Role of functions

  • The function iswell organizedThe.Reusableof code segments used to implement a single or associated functionality
  • Functions can raiseHighly applied modularitycap (a poem)Reuse of code
  • python built-in functions:/zh-cn/3.10/library/

1.2 Function definitions

  • def: function definition keywords
  • function_name: Function name
  • (): where the parameter list is placed, can be empty
  • parameter_list: Optional, specify the parameters to be passed to the function.
  • comments: Optional, specify comments for the function
  • function_body: Optional, specify the function body
def function_name([parameter_list]):
    [''' comments ''']
    [function_body]

Notes on defining functions:

  • Indentation: python judges blocks of code by strict indentation.

    • Function bodies and comments must be indented relative to the def keyword, usually by 4 spaces.
    • pycharm auto-formatting shortcuts:ctrl+alt+L
  • Defining empty functions

    • utilizationpass statement placeholder
    • Write function comment comments,

1.3 Function calls

  • function_name: name of the function
  • parameter_value: optional, specify the value of each parameter.
function_name([parameter_value])

1.4 Parameters of functions

1.4.1 Passing of parameters

  • Formal parameters:Defining FunctionsThe parameter in parentheses after the name of the function is used when
  • Actual parameters:call functionThe parameter in parentheses after the name of the function is used when
# a, b, c are formal parameters
def demo_func(a, b, c):
    print(a, b, c)

# 1, 2, 3 are actual parameters
demo_func(1, 2, 3)

1.4.2 Parameter types

1.4.2.1 Positional parameters (required parameters)

  • Quantity must be the same as when defined
  • The position must be the same as when defined
def demo_func(a, b, c):
    print(a, b, c)

# 1 to a, 2 to b, 3 to c #
demo_func(1, 2, 3)

1.4.2.2 Keyword parameters

  • utilizationThe name of the formal parameter determines the value of the input parameter
  • Doesn't need to be exactly the same position as the formal parameter
def demo_func(a, b, c):
    print(a, b, c)

demo_func(a=1, b=2, c=3)

1.4.2.3 Variable parameters

  • Variable parameters are also known asindeterminate length parameter (math.)
  • The actual parameters in the incoming function can be any number of them
  • common form
    • *args
    • **kwargs
1.4.2.3.1 *args
  • Receive anyMultiple actual parametersand put it into atuplecenter
  • Use the already existinglistingsmaybetupleAs a variable argument to a function, the name of the list can be preceded by the*
def print_language(*args):
    print(args)

print_language("python", "java", "php", "go")

params = ["python", "java", "php", "go"]
print_language(*params)
1.4.2.3.2 **kwargs
  • Receive any number ofActual parameters that are explicitly assigned like keyword parametersand put it into adictionariescenter
  • Using an already existing dictionary as a variable argument to a functionYou can prefix the name of the dictionary with**
def print_info(**kwargs):
    print(kwargs)

print_info(Tom=18, Jim=20, Lily=12)

params = {'Tom':18, 'Jim':20, 'Lily':12}
print_language(**params)

1.4.5 Setting default values for parameters

  • When defining a function you canSpecify default values for formal parameters
  • The formal parameter that specifies the default value must be placed at the end of all parameters.Otherwise, a syntax error will be generated
  • param=default_value: Optional, specifies the parameter and sets the default value for the parameter to default_value.
  • Setting default valuesUnavailable objects must be used, mutable objects are not available, e.g., lists, dictionaries.
def function_name(..., [param=default_value]):
    [function_body]

1.5 Function Return Values

value: optional, specify the value to be returned

def function_name([parameter_list]):
    [''' comments ''']
    [function_body]
    return [value]

2. python lambda expressions

2.1 Anonymous functions

  • Functions without names
  • Creating Anonymous Functions with Lambda Expressions

2.2 Scenarios of use

  • Need a function, but don't want to bother naming the function
  • Usually in thisScenarios where the function is only used once
  • You can specify short callback functions

2.3 Grammar

  • result: calls a lambda expression.
  • [arg1 [, arg2, .... , argn]]: optional, specifies the list of parameters to pass
  • expression: mandatory, specify an expression that realizes a specific function.
result = lambda [arg1 [, arg2, .... , argn]]: expression

2.4 Examples

L=[('b',2),('a',1),('c',3),('d',4)]

# 2, using the parameter cmp sort
sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))
# Results:
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# 3, using the parameter key sort
sorted(L, key=lambda x:x[1])
# Results:
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

to this article on python function and python anonymous function lambda article is introduced to this, more related python anonymous function lambda content, please search my previous articles or continue to browse the following related articles I hope you will support me more in the future!