11 summary and operation (function related part)

Posted by bogdaniel on Mon, 28 Feb 2022 12:59:13 +0100

1, Summary

  1. Function basis

    1. Sentiment: a function is a code encapsulation that implements a specific function

    2. Classification:
      #. the functions are classified according to who created them: system functions (such as print, type, etc.) and user-defined functions (self created)

    3. Syntax:
      Def function name (formal parameter list): - def: keyword, fixed writing method; Function name: self naming
      Function description document - formal parameter list: exists in the form of 'variable name 1, variable 2...'. There can be no formal parameters or multiple formal parameters
      Function body - function description document: the essence is multi line comments; Function body: one or more statements, that is, code

  2. Call function

    1. The function body will not be executed when defining a function, but only when calling

    2. Calling function syntax: function name (argument list) - write out what you need

    3. Define a function before calling it

    4. Argument list: exists in the form of 'data 1, data 2...'. Arguments are the data that is really passed to the function through formal parameters. The number of arguments is determined by the number of formal parameters

    5. Pass parameter: assign values to formal parameters in turn

    6. Function calling process: 1. Return to the position defined by the function; 2. Transfer parameters; 3. Execute function body; 4. Determine the return value; 5 will go to the location of the function call, and then proceed to the next execution

  3. Function parameters

    1. Location parameters and keyword parameters (depending on the transfer method of actual parameters):

      • Position parameter - the first corresponding parameter of the actual parameter, the first formal parameter, and so on, with one-to-one correspondence in position

      • When the parameter name is not changed, the parameter name can be added directly, that is, when the parameter name is not changed, the result is the "parameter name"

      • Mixed use of two parameters – the location parameter must be in front of the keyword parameter

    2. Parameter default value:

      • When defining a function, you can assign default values to formal parameters. When calling a function, there are already default parameters, and you can not pass parameters
    3. Parameter type description:

      • Assign the default value. The default value is what type, and the parameter type description is what type, such as' x: str '. The description after the colon does not affect the program operation, so as to prompt
    4. Variable length parameters:

      • By adding a * or * * in front of the formal parameter, the parameter can become an indefinite length parameter, which can receive multiple arguments. Add a * before the formal parameter, and the variable length formal parameter will become a tuple. The data in the tuple is the received argument; Join two * in the shape, and the variable length parameter will become a dictionary. For the elements (key value pairs) in the dictionary, the value will become the value of the argument, and the key is the name of the parameter;

      • Add: if the function parameter is after the parameter with *, the latter parameters must use keyword parameters when calling

  4. Return value

    1. Return value: the data passed from inside the function to outside the function
    2. How to determine the return value of the function (how to transfer the internal data of the function to the outside): in the function body, put the data to be returned after return
    3. How to get the function return value (how to get the data passed inside the function outside the function): get the result of the function expression outside the function. Usually, a variable is used to receive the result of the function expression. The function has no return and returns None
    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

2, Homework

  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_dict(dict1):
        new_dict1 = dict({(values, keys) for keys, values in dict1.items()})
        print(new_dict1)
    
    exchange_dict({'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 extract_letter(str2):
        new_str2 = ''
        for i in str2:
            if 'a' <= i <= 'z' or 'A' <= i <= 'Z':
                new_str2 += i
        print(new_str2)
    
    
    extract_letter('12a&bc12d-+')
    
  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 start_letter(str3):
        start_str = str3[0]
        if not ('a' <= start_str <= 'z'):
            print(str3)
        else:
            a3 = chr(ord(start_str) - 32)
            print(a3 + str3[1:])
    
    
    start_letter('12asd')
    
  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 end_str(str1, str2):
        if str1[-len(str2):] == str2:
            print(True)
        else:
            print(False)
    
    
    end_str('abc231ab', 'ab')
    
  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 num_str(str5):
        for i in str5:
            if not '0' <= i <= '9':
                print(False)
                break
        else:
            print(True)
    
    
    num_str('1234921')
    
  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 upper_str(str6):
        new_str6 = ''
        for i in str6:
            if 'a' <= i <= 'z':
                a6 = chr(ord(i) - 32)
                new_str6 += a6
            else:
                new_str6 += i
        print(new_str6)
    
    
    upper_str('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 flush_right_str(str7, str77, width):
        if len(str7) < width:
            time = width - len(str7)
            new_str7 = str77 * time + str7
            print(new_str7)
        else:
            print('Not valid, please re-enter the width')
    
    
    flush_right_str('abc', '^', 7)
    
  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_list(list8, element):
        new_list = []
        for index, element1 in enumerate(list8):
            if element1 == element:
                new_list.append(index)
        print(new_list)
    
    
    index_list([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 i in sequence:
            count += 1
        print(count)
    
    
    count_number((1, 34, 'a', 45, 'bbb'))
    
  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 max_value(sequence):
        if type(sequence) == list:
            max_value1 = sequence[0]
            for i in sequence:
                if max_value1 < i:
                    max_value1 = i
            print(max_value1)
        elif type(sequence) == str:
            max_value1 = ord(sequence[0])
            for i in sequence:
                if max_value1 < ord(i):
                    max_value1 = ord(i)
            print(chr(max_value1))
        elif type(sequence) == dict:
            max_value1 = 0
            for i in sequence:
                if max_value1 < sequence[i]:
                    max_value1 = sequence[i]
            print(max_value1)
    
    
    max_value('abcdpzasdz')
    
  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 in_sequence(sequence, element):
        for i in sequence:
            if i == element:
                print(True)
                break
        else:
            print(False)
    
    
    in_sequence((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 slicing_str(str, old_str, new_str):
    result = new_str.join(str.split(old_str))
    print(result)


slicing_str('how are you? and you?', 'you', 'me')

Topics: Python