Python function foundation

Posted by manmanman on Mon, 28 Feb 2022 13:42:29 +0100

Function basis

1. Define function

1. What is a function

  1. concept

    A function is the encapsulation of the code that implements a specific function - > a function corresponds to a function (the function stored in the function)

  2. Classification (by who created the function)

    • System functions - there are functions that have been created in Python language (Python's own functions), such as print, input, type, id, max, min, sorted, sum, etc
    • Custom function - a function created by the programmer himself

2. Define function (build machine)

  1. Syntax:

    def Function name(parameter list ):
        Function description document
        Function body
  2. explain:

    • def - keyword; Fixed writing

    • Function name - named by the programmer;

      Requirement: identifier, not keyword

      Scope: see the name to know the meaning (see the function name to roughly know what the function is)
      Do not use the system function name, class name, module name
      All letters are lowercase, and multiple words are separated by underscores

    • (): - Fixed writing

    • Formal parameter list - exists in the form of 'variable name 1, variable name 2, variable name 3,...', where each variable is a formal parameter; Formal parameters can be none or multiple. Formal parameters can transfer data outside the function to the inside of the function; How many formal parameters are needed when defining a function? It depends on whether additional data is needed to implement the function. How many parameters are needed

    • Function description document - the essence is to keep an indented multi line comment with def; It is used to describe the function, parameters and return value of a function

    • Function body - one or more statements that maintain an indentation with def, which is essentially the code to realize the function. (circuit structure and mechanical mechanism)

# Exercise 1: write a function to sum two numbers
def sum2(num1, num2):
    (Function description area)Find the sum of any two numbers
    :param num1: (Parameter description) Number 1
    :param num2: Number 1
    :return: (Return value description) None
    print(num1 + num2)

sum2(10, 20)
# Exercise 2: write a function to count the number of numeric characters in a specified string
def count_number(str1):
    """Number of statistics characters"""
    count = 0
    for x in str1:
        if x.isdigit():
            count += 1

count_number('ajhf1238 Shanhaijing 02')
count_number('2791 of the number')
# Exercise 3: define a function to get the ten digits of any integer (both positive and negative)
def get_tens_digit(num):
    """Get ten digits"""
    if num < 0:
        num *= -1
    print(num // 10 % 10)

# Exercise 4: define a function to get all numeric elements in the specified list
def get_numbers(list1):
    """Get numeric element"""
    new_list = []
    for x in list1:
        if type(x) in (int, float):

get_numbers([19, 'yes d', 23.8, True, None])
# Exercise 5: define a function to get the common part of two strings
def get_common_char(str1, str2):
    """Gets the common part of two strings"""
    result = set(str1) & set(str2)

get_common_char('abcn', '123ba92')
# Exercise 6: define a function exchange Dictionary of keys and values
def change_key_value(dict1):
    new_dict = {}
    for key in dict1:
        new_dict[dict1[key]] = key

change_key_value({'a': 10, 'b': 20, 'c': 30})

2. Call function

  1. Important conclusion: the function will not be executed when defining the function, but only when calling

  2. Syntax:

    Function name(Argument list)
  3. explain:

    • Function name - call the function of which function you need, and write the function name of which function you want to call

      Note: the function name here must be the function name of the defined function

    • () - Fixed writing

    • Argument list - exists in the form of 'data 1, data 2, data 3,...'; Arguments are the data that is really passed to the function through formal parameters; The number of arguments is determined by the formal parameters. By default, the number of arguments is required when the function is called

  4. Function call procedure:

    When the code executes the function call statement:
    Step 1: return to the position defined by the function
    Step 2: pass parameters (the process of assigning values to formal parameters with actual parameters). When passing parameters, you must ensure that each formal parameter has a value
    Step 3: execute the function body
    Step 4: determine the return value
    Step 5: return to the location of the function call, and then execute it later

3. Parameters of function

1. Location parameter and keyword parameter - according to the different transfer methods of the arguments, the arguments of the function are divided into these two types

  1. Location parameters

    When calling a function, separate multiple data directly with commas, and the actual parameters and formal parameters correspond to each other in position

  2. Keyword parameters

    When calling the function, add 'formal parameter name =' in front of the data, and the actual parameter and formal parameter are corresponding by the formal parameter name

  3. Mixed use of two parameters

    It is required to ensure that the location parameter is in front of the keyword parameter

def func1(x, y, z):
    print(f'x:{x}, y:{y}, z:{z}')

func1(10, 20, 30)
func1(20, 10, 30)
func1(x=100, y=200, z=300)
func1(z=3, x=1, y=2)
func1(10, y=20, z=30)
func1(10, z=30, y=20)
func1(10, 20, z=30)
# func1(10, b=20, 30)   # report errors! SyntaxError: positional argument follows keyword argument

2. Parameter default value

  1. When defining a function, you can assign default values to formal parameters. When calling a function, there are already default parameters. You can directly use the default values without passing parameters.
  2. If you assign default values to some parameters, you must ensure that the parameters without default values precede the parameters with default values

3. Parameter type description

Parameter type description: specify the parameter type when defining the function

  1. Add type description for parameters without default value

    Formal parameter name:data type
  2. For parameters with default values, the type of default value is the type of parameter

4. Variable length parameters

Variable length parameter with *:

  • Add * before the formal parameter, and the parameter becomes a tuple, which is used to receive all the corresponding arguments (the arguments are the elements in the tuple)
  • Remember: if the function parameter is after the parameter with *, the latter parameters must use keyword parameters when calling

4. Return value of function

What is a return value

  1. significance:

    • The return value is the data passed from inside the function to outside the function
  2. How to determine the return value (how to pass the data inside the function to the outside of the function as the return value):

    • In the function body, put the data to be returned after return;
    • The return value of the function is the value after return. If there is no return, the return value is None
  3. How to get the return value (how to get the data passed from inside the function outside the function):

    • Obtain the result of the function call expression outside the function;
    • The value of the function call expression is the return value of the function
  4. When to return a value:

    • If new data is generated by implementing the function of the function, the new data is returned as the return value
def sum2(n1, n2):
    # n1 = 10; n2 = 20
    result = n1 + n2     # result = 30
    return result      # return 30

a = sum2(10, 20)      # The value of the function call expression is the return value of the function


  1. Write a function to exchange the key and value of the specified dictionary.

      for example:dict1={'a':1, 'b':2, 'c':3}  -->  dict1={1:'a', 2:'b', 3:'c'} 
    def change_key_value(dict1: dict):
        dict0 = {}
        for key, value in dict1.items():
            dict0.setdefault(value, key)
        return dict0
    a = change_key_value({'a': 1, 'b': 2, 'c': 3})
  2. Write a function to extract all the letters in the specified string, and then splice them together to produce a new string

       for example: afferent'12a&bc12d-+'   -->  'abcd'  
    def get_alphabet(str1: str):
        str0 = ''
        for x in str1:
            if 'a' <= x <= 'z' or 'A' <= x <= 'Z':
                str0 += x
        return str0
    a = get_alphabet('1acXS3w4')
  3. Write your own capitalize function, which can turn the first letter of the specified string into uppercase letters

      for example: 'abc' -> 'Abc'   '12asd'  --> '12asd'
    def turn_majuscule(str1: str):
        for x, y in enumerate(str1):
            if 'a' <= y <= 'z':
                result = str1.replace(y, chr(ord(y) - 32), x+1)
        return result
    a = turn_majuscule('12abc')
  4. Write your own endswitch function to judge whether a string has ended with the specified string

       for example: String 1:'abc231ab' String 2:'ab' The result of the function is: True
            String 1:'abc231ab' String 2:'ab1' The result of the function is: False
    def judge_ending(str1: str, str0: str):
        if str1[-len(str0):] == str0:
    judge_ending('abc231ab', 'ab1')
  5. Write your own isdigit function to judge whether a string is a pure digital string

       for example: '1234921'  result: True
             '23 function'   result: False
             'a2390'    result: False
    def judge_pure_number(str1: str):
        for x in str1:
            if x < '0' or x > '9':
  6. Write your own upper function to change all lowercase letters in a string into uppercase letters

        for example: 'abH23 good rp1'   result: 'ABH23 good RP1'   
    def minuscule_turn_majuscule(str1: str):
        str0 = ''
        for x in str1:
            if 'a' <= x <= 'z':
                x = chr(ord(x) - 32)
            str0 += x
        return str0
    a = minuscule_turn_majuscule('abH23 good rp1')
  7. Write your own rjust function to create a string whose length is the specified length. The original string is right aligned in the new string, and the rest is filled with the specified characters

       for example: Original character:'abc'  width: 7  character:'^'    result: '^^^^abc'
            Original character:'how are you'  width: 5  character:'0'    result: '00 how are you'
    def rjust_function(str1: str, width: int, element):
        result = ''
        for x in range(width - len(str1)):
            result += element
        result += str1
        return result
    a = rjust_function('how are you', 5, '0')
  8. Write your own index function to count all the subscripts of the specified elements in the specified list. If there is no specified element in the list, return - 1

       for example: list: [1, 2, 45, 'abc', 1, 'Hello', 1, 0]  element: 1   result: 0,4,6  
            list: ['Zhao Yun', 'Guo Jia', 'Zhuge Liang', 'Cao Cao', 'Zhao Yun', 'Sun Quan']  element: 'Zhao Yun'   result: 0,4
            list: ['Zhao Yun', 'Guo Jia', 'Zhuge Liang', 'Cao Cao', 'Zhao Yun', 'Sun Quan']  element: 'Guan Yu'   result: -1         
    def index_function(list1: list, element):
        for x in range(len(list1)):
            if list1[x] == element:
                return x
            return -1
    a = index_function([1, 2, 45, 'abc', 1, 'Hello', 1, 0], 1)
  9. Write your own len function to count the number of elements in the specified sequence

        for example: sequence:[1, 3, 5, 6]    result: 4
             sequence:(1, 34, 'a', 45, 'bbb')  result: 5  
             sequence:'hello w'    result: 7
    def count_number(sequence):
        count = 0
        for x in sequence:
            count += 1
        return count
    a = count_number('hell0 wo')
  10. Write your own max function to get the maximum value of the elements in the specified sequence. If the sequence is a dictionary, take the maximum value of the dictionary value

      for example: sequence:[-7, -12, -1, -9]    result: -1   
           sequence:'abcdpzasdz'    result: 'z'  
           sequence:{'Xiao Ming':90, 'Zhang San': 76, 'Monkey D Luffy':30, 'floret': 98}   result: 98
    def get_max_number(sequence):
        if type(sequence) == dict:
            result = 0
            for x in sequence.values():
                if x > result:
                    result = x
            result = sequence[0]
            for y in sequence[1:]:
                if y > result:
                    result = y
        return result
    a = get_max_number({'Xiao Ming':90, 'Zhang San': 76, 'Monkey D Luffy':30, 'floret': 98})
  11. Write a function to realize its own in operation and judge whether the specified element exists in the specified sequence

        for example: sequence: (12, 90, 'abc')   element: '90'     result: False
             sequence: [12, 90, 'abc']   element: 90     result: True     
    def judge_in(sequence, element):
        for x in sequence:
            if x == element:
    judge_in([12, 90, 'abc'], 90)
  12. Write your own replace function to convert the old string specified in the specified string into the new string specified

        for example: Original string: 'how are you? and you?'   Old string: 'you'  New string:'me'  result: 'how are me? and me?'
    def replace_function(str2: str, str1:str, str0: str):
        result = ''
        x = 0
        while x < len(str2):
            if str1 == str2[x:x+len(str1)]:
                result += str0
                x += len(str1)
                result += str2[x]
                x += 1
        return result
    a = replace_function('how are you? and you?', 'you', 'me')

Topics: Python Back-end