Functions in Python

Posted by dabaR on Mon, 10 Jan 2022 18:10:32 +0100

Functions in Python (2)

1. Anonymous functions

  • Grammar:

    Function name = lambda parameter list: Return value
    Amount to:
    def Function name(parameter list):
        return Return value
  • Be careful:

    • Anonymous functions can only implement functions that complete a function in one sentence of code
    • Anonymous functions are called as normal functions
    • Anonymous function parameters cannot be typed using colon syntax

2. Scope of Variables - Scope that Variables can use

Divide variables into global and local variables according to their scope

  • global variable

    • A variable that is not defined in a function or class is a global variable
    • Global variables are scoped from definition to program end
  • local variable

    • A variable defined within a function is a local variable
    • Local variables are scoped from definition to function end
  • Function Call Procedures (Changes in Memory)

    • Each time a function is called, a temporary memory area is automatically opened in the stack interval for the function to store the local variables defined in the function.
    • The system will automatically release this memory when the function call ends
  • Globals and nonlocal - can only be used in function bodies

    • global

      • To modify the value of a global variable in a function, you need to explain the variable with globals before.
      • Defining a global variable in a function requires explaining it in globals before.
      global Variable Name
    • nonlocal

      • If you need to modify the value of a local variable locally, you need to use nonlocal for explanation

3. Higher Order Functions with Arguments

Important conclusion: defining a function in python is defining a variable whose type is function and whose name is the variable name
  • Functions in Parameters of Arguments Higher Order Functions-Functions

  • Higher Order Functions with Common Arguments

    • max,min,sorted
    max(sequence, key=function)
    Functional requirements:a.There is one and only one parameter (this parameter points to each element in the previous sequence)
           b.There is a return value (the return value is the comparison object)
    • map
    map(function, sequence)  -   Generates a new sequence by transforming all elements in the sequence according to the specified rules
     Functional requirements: a. There is one parameter (pointing to elements in the sequence)
            b. A return value is required (elements in the new sequence, describing the relationship between the new sequence element and the original sequence element)
    map(function, Sequence 1, Sequence 2)
    Functional requirements: a. Several sequences have several parameters, the first pointing to the element in sequence 1 and the second pointing to the element in sequence 2.
            b. A return value is required (elements in the new sequence, describing the relationship between the new sequence element and the original sequence element)
    Note: Functions can be followed by N Sequence, requires this N Number of elements in sequence must be consistent;How many sequences does a function take?
    • reduce
    from functools import reduce
    reduce(function, sequence, initial value)
    Function: a. There are and only two parameters
            First parameter: the first point to the initial value, and the second point to the result of the last operation (which can be viewed directly as the initial value)


  1. The coordinates of each point are saved in the list points (coordinates are tuple, the first value is x-coordinate, the second value is y-coordinate)

    points = [
      (10, 20), (0, 100), (20, 30), (-10, 20), (30, -100)

    The following problems are solved using higher order functions with arguments

    1) Get the point with the largest y coordinate in the list

    print(max(points, key=lambda y: y[1]))

    2) Get the point with the smallest x-coordinate in the list

    print(min(points, key=lambda x: x[0]))

    3) Get the farthest point from the origin in the list

    print(max(points, key=lambda s: s[0]**2 + s[1]**2))

    4) Sort points from large to small by the distance from the point to the x-axis

    print(sorted(points, key=lambda s: s[1] if s[1] >= 0 else -s[1], reverse=True))
  2. Find the element with the highest absolute value in the list nums

    nums = [12, 64, 47, -82, 45, 78]
    print(max(nums, key=lambda n: n if n >= 0 else -n))
  3. There are already two lists A and B. Use the map function to create a dictionary. The elements in A are key s, and the elements in B are value s.

    A = ['name', 'age', 'sex']
    B = ['Zhang San', 18, 'female']
    # New dictionary: {'name':'Zhang San','age': 18,'sex':'female'}
    print(dict(map(lambda key, value: (key, value), A, B)))
  4. There are already three lists representing the names, disciplines, and class numbers of five students. Use map to spell the three lists into a dictionary that represents the class information for each student

    names = ['Xiao Ming', 'Floret', 'Little Red', 'King']
    nums = ['1906', '1807', '2001', '2004']
    subjects = ['python', 'h5', 'java', 'python']
    # Results: {'Xiaoming':'python 1906','Xiaohua':'h51807','Xiaohong':'java2001','King':'python 2004'}
    print(dict(map(lambda name, sub, num: (name, sub + num), names, subjects, nums)))
  5. There is already a list message that uses reduce to calculate the sum of all the numbers in the list (using list derivation and not list derivation)

    message = ['Hello', 20, '30', 5, 6.89, 'hello']
    # Result: 31.89
    # List Derivation
    print(sum([x for x in message if type(x) == int or type(x) == float]))
    # reduce
    from functools import reduce
    print(reduce(lambda sums, item: sums + (item if type(item) == int or type(item) == float else 0), message, 0))
  6. It is known that a list of dictionaries holds the results of each student in each subject.

    1) Calculate and add the average score for each student

    2) Sort by average score from high to low

    studens = [
      {'name': 'stu1', 'math': 97, 'English': 67, 'Chinese': 80},
      {'name': 'stu2', 'math': 56, 'English': 84, 'Chinese': 74},
      {'name': 'stu3', 'math': 92, 'English': 83, 'Chinese': 78},
      {'name': 'stu4', 'math': 62, 'English': 90, 'Chinese': 88}
    # Calculate average score
    studens = [
      {'name': 'stu1', 'math': 97, 'English': 67, 'Chinese': 80, 'avg':81},
      {'name': 'stu2', 'math': 56, 'English': 84, 'Chinese': 74, 'avg':71},
      {'name': 'stu3', 'math': 92, 'English': 83, 'Chinese': 78, 'avg':87},
      {'name': 'stu4', 'math': 62, 'English': 90, 'Chinese': 88, 'avg':80}
    # Sort by average score from high to low
    # Calculate average score
    # Method One
    print(list(map(lambda stu: {'name': stu['name'], 'math': stu['math'], 'English': stu['English'], 'Chinese': stu['Chinese'], 'avg': int((stu['math'] + stu['English'] + stu['Chinese']) / 3)}, studens)))
    # Method 2
    for stu in studens:
        stu['avg'] = int((stu['math'] + stu['English'] + stu['Chinese']) / 3)
    # Sort by average score from high to low
    print(sorted(studens, key=lambda stu: stu['avg'], reverse=True))

Topics: Python