day11 summary and assignment

Posted by nocniagenti on Tue, 01 Mar 2022 09:22:31 +0100


I 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)

      1. 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
      2. Custom function - a function created by the programmer himself
  2. Define function

    1. grammar

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

      def     -       keyword; Fixed writing
       Function name   -       Named by the programmer himself;
                      Requirement: identifier, not keyword
                      Scope: see name and meaning(When you see the function name, you probably 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
       parameter list     -  with'Variable name 1, Variable name 2, Variable name 3,...'Each variable here 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 harmony def Keep an indented multiline comment; It is used to describe the function, parameters and return value of a function
       Function body     -   and def Keeping one or more statements indented is essentially the code to realize the function.
    3. practice

      # 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 find the result of 5 times 6
      def product(num1, num2):
          print(num1 * num2)
      product(5, 6)
      product(99, 120)
      # Exercise 3: 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 4: 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 5: define a function to get all the 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 6: 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 7: 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})

II Call function

  1. 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    -    with 'Data 1, Data 2, Data 3,...' The form of existence; An argument is the data that is really passed to the inside of a function through a formal parameter
                      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 on parameters(The process of assigning values to formal parameters with arguments),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
            def func1():
                # print('abc'[10])
                print('====hello python=====')
            def sum2(num1, num2):
                """(Function description area)Find the sum of any two numbers"""
                # Transmission parameter: num1 = 10; num2 = 20
                print(num1 + num2)    # print(10 + 20)  -> print(30)
            sum2(10, 20)
            sum2(100, 200)

III Parameters of function

  1. Positional parameters and keyword parameters - the arguments of the function are divided into these two types according to the different transmission methods of the arguments

    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 defaults

    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

      def func2(x=1, y=2, z=3):
          print(f'x:{x}, y:{y}, z:{z}')
      func2(10, 20, 30)
      func2(100, 200)
      def func3(x, y, z=3, t=4):
      def connect(host, user, pw, port=3306):
  3. Parameter type description - specify the parameter type when defining the function

    1. Add type description for parameters without default value

      Parameter name: data type

    2. For parameters with default values, the type of default value is the type of parameter

  4. Indefinite length parameter

    1. Indefinite length parameter with *

      1. 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)

      2. Remember: if the function parameter is after the parameter with *, the latter parameters must use keyword parameters when calling

        # Define a function to sum multiple numbers
        def sum1(*nums):
        sum1(10, 20)
        sum1(2, 34, 5)
        sum1(10, 29, 38, 9, 19)
        def student_info(name, *score):
            print(name, score)
        student_info('Xiao Ming')
        student_info('floret', 397, 420)
        student_info('Zhang San', 397, 328, 300)

    IV Return value of function

    1. Meaning: the return value is the data passed from the inside of the function to the outside of 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):

      1. In the function body, put the data to be returned after return;
      2. 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):

      1. Obtain the result of the function call expression outside the function;
      2. The value of the function call expression is the return value of the function
    4. When the return value is needed: if the function of the implementation function generates new data, the new data will be 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
      def func1():
          return 100
      # b = 100
      b = func1()
      print(100 * 2, func1() * 2)
      print(100 < 200, func1() < 200)
      list1 = [100, 200, func1()]
      def func2():
          return 'abc'
      print('abc'[-1], func2()[-1])    # 'abc'[-1]
      def sum3(x, y):
          return x + y
      result = sum3(100, 230)


    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 exchange_key_value(dict1:dict):
          """Exchange dictionary keys and values"""
          result = {value:key for key,value in dict1.items()}
          return result
    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, '12a&bc12d - +' -- > 'ABCD' is passed in  
      def get_letters(str1:str):
          """Extracts all letters in the specified string"""
          str2 = ''
          for i in str1:
              if 'a' <= i <= 'z' or 'A' <= i <= 'Z':
                  str2 += i
          return str2
    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 change_initial(str1:str):
          """Converts the first letter of the specified string to uppercase"""
          str2 = ''
          first = str1[0]
          if 'a' <= first <= 'z':
              first = chr(ord(first) - 32)
              str2 = first + str1[1:]
              return str2
              return str1
    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' function result: True
      #        String 1:'abc231ab' string 2:'ab1' function result: False
      def new_endswith(str1:str, str2:str):
          """Determines whether a string has ended with the specified string"""
          a = len(str2)
          result = (str1[-a:] == str2)
          return result
    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 new_isdigit(str1:str):
          for i in str1:
              if not'0' <= i <= '9':
                  return False
              return True
    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 new_upper(str1:str):
          str2 = ''
          for i in str1:
              if 'a' <= i <= 'z':
                  i = chr(ord(i) - 32)
              str2 += i
          return str2
    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 characters: '^' result: '^ ^ ^ ^ abc'
      #       Original character: 'how are you' width: 5 characters: '0' result: '00 how are you'
      def new_rjust(str1:str, width:int, char1:str):
          a = len(str1)
          str2 = char1 * (width - a) + str1
          return str2
    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 new_index(list1:list, element):
          list2 = []
          if element in list1:
              for index,item in enumerate(list1):
                  if item == element:
              return list2
              return -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 new_len(sequence):
          count = 0
          for i in sequence:
              count += 1
          return count              
    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: {'Xiaoming': 90, 'Zhang San': 76, 'Luffy': 30, 'Xiaohua': 98} result: 98
      def max_value(sequence):
         if type(sequence) == list:
             return sequence[0]
         elif type(sequence) == str:
             max_value = sequence[0]
             for i in range(1,len(sequence)):
                 if max_value < sequence[i]:
                     max_value = sequence[i]
             return max_value
             max_value = sequence['Xiao Ming']
             for i in sequence:
                 if max_value < sequence[i]:
                     max_value = sequence[i]
             return max_value
    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 new_in(sequence, item):
          for i in sequence:
              if i == item:
                  return True
              return False
    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 new_replace(str1:str, str2, str3):
          if str2 in str1:
              new_str = str3.join(str1.rsplit(str2))
              return new_str

Topics: Python