当前位置:网站首页>Summary -day11

Summary -day11

2022-06-12 03:05:00 Soybeans are not soybeans

summary -day11

Recognize functions

  1. What is a function
 A function is the encapsulation of code that implements a specific function 

1) Concept 
 A function is the encapsulation of code that implements a specific function -->  A function corresponds to a function ( Function storage function )

2).  classification ( Sort functions by who created them )
a.  System function :  from python The language has already created functions (python Self contained function ), for example : print, input , type , id , max , min , sorted , sum etc. 
b.  Defined function :  Functions created by programmers themselves 
  1. Defined function ( Build a machine )
 grammar :
def  function ( Parameter list ):
     Function documentation 
     The body of the function 
    
 explain :
def   -   keyword :  Fixed writing 
 Function name  -   Named by the programmer himself 
         ( Naming requirements )- Is an identifier. , It can't be a keyword .. Range -  Know what you know .. Do not use the system function name 、 Class name 、 Module name 、 The letters are all lowercase , Multiple words are separated by underscores 
()    -   Fixed writing 
 Parameter list  -  With ' Variable name 1, Variable name 2, Variable name 3,...' There is a form of , Every variable here is a formal parameter ; There can be no formal parameters , There can be more than one 
           Formal parameters can transfer data outside the function to the inside of the function ;
           Do you need formal parameters when defining a function , You need to see if you need additional data to implement the function , How many do you need 
 Function documentation  -  The essence is multi line comments ; For the function of the function 、 Parameters and return values .( Instructions )
 The body of the function   -   and def One or more statements that hold an indent , The essence is the code to realize the function .( Circuit structure and mechanical structure )

practice 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 ) First number  :param num2: ( Parameter description ) The second number  :return: ( Return value description ) Sum of two numbers  """
    return num1+num2

practice 2: Write a function to find 5 multiply 6 Result

def cheng(num1,num2):
    return num1*num2

practice 3: Write a function to count the number of numeric characters in a specified string

def count1(str1):
    count = 0
    for i in str1:
        if '0'<=i<='9':
            count+=1
    return count

practice 4: Define a function to get any integer ( Both positive and negative ) The tens of

def ten_num(int1):
    if int1>=10:
        int2 = int1 // 10 % 10
        return int2
    elif int1 <= -10:
        int2 = int1 // -10 % 10
        return int2
    else:
        return ' empty '

practice 5: Define a function , Gets all the numeric elements in the specified list

def count3(list1):
    for i in list1:
        if type(i) in [int,float]:
            print(i,end=' ')
    print()

practice 6: Define a function , Get the public part of another string

def both(str1,str2):
    res = set(str1)&set(str2)
    for i in res:
        print(i,end=' ')
    print()

practice 7: Define the keys and values of a function exchange dictionary

def exchange1(dict1):
    dict2 = {
    }
    for i in dict1:
        a,b = dict1[i],i
        dict2[a]=b
    print(dict2)

Call function

  1. Call function
1)  Important conclusions : When defining a function, it will not execute the function , Only when called 

2)  Call function 
 grammar :
 Function name ( Argument list )

 explain :
 Function name   -   Call any function you need , Write the function name of the function you want to call 
       -   Be careful : The function name here must be the function name of the defined function 
       -  Fixed writing 
 Argument list  -  With ' data 1, data 2, data 3...' There is a form of ; 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 function to be called has as many formal parameters as it needs as many arguments to be called 
3)  Function call procedure 
 When the code executes the function call statement 
 First step :  Return to the position defined by the function 
 The second step :  The ginseng ( The process of assigning values to formal parameters with arguments ), When passing parameters, you must ensure that each formal parameter has a value 
 The third step : Execute function body 
 Step four : Determine the function value 
 Step five : Return to the location of the function call , Then go back 

The parameters of the function

  1. Position function and keyword parameters - Depending on how arguments are passed , Divide the arguments of a function into two types
1)  Positional arguments 
 When calling a function, separate multiple data directly with commas , Arguments and formal parameters correspond to each other in position 

2) Key parameters 
 When you call a function , Add... Before the data ’ Sexual parameter name =‘, Arguments and formal parameters are corresponding by formal parameter names 


3)  The two parameters are mixed 
 It is required to ensure that the position parameter precedes the keyword parameter 
  1. Parameter default
 When defining a function, you can assign default values to formal parameters , When calling a function, there are already default parameters. You don't need to pass parameters , Use the default value 

 If you assign default values to some parameters , It must be ensured that the parameter without default value precedes the parameter with default value 
def func(x=1,y=1,z=1):
    print(f'x:{
      x},y:{
      y},z:{
      z}')


func()
  1. Parameter type description
 Define type descriptions :  When defining a function, specify the parameter type 
1) Add type description for parameters without default value 
 The name of the parameter : data type 

2)  Parameters with default values , The type of default value is the type of parameter 
  1. Indefinite length parameter
1)  belt * Indefinite length parameter of 
 Prefix formal parameters *, Then this parameter becomes a tuple , Used to receive all the corresponding arguments ( Arguments are elements in tuples )

 Be careful :  If the arguments of the function are with * After the parameter of , Then the following parameters must use keyword parameters when calling 

The return value of the function

  1. What is the return value
1)  significance :  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 of a function ( How to transfer the data inside the function to the outside of the function as a worry drawing ): In the body of a function , Write the data to be returned to return Back 
                                                              return What is the following value , The return value is 
                                                               without return, The return value is None
3) How to get the return value ( How to get the data passed from the function outside the function ): Get the result of the function call expression outside the function 
4) When do I need to return a value : If you implement the function of the function and generate new data , Return the new data as a return value 
  1. Write a function , Exchange the specified dictionary key and value.

       for example :dict1={
          'a':1, 'b':2, 'c':3}  -->  dict1={
          1:'a', 2:'b', 3:'c'}  
    def exchange(dict1):
        dict2 = {
          }
        for i in dict1:
            dict2[dict1[i]] = i
        print(dict2)
    
  2. Write a function , Extract all letters in the specified string , Then spliced together to produce a new string

        for example :  Pass in '12a&bc12d-+'   -->  'abcd'  
    def all_alp(str1:str):
        for i in str1:
            if 'a' <=i<='z' or 'A' <=i<='Z':
                resel = ''.join(i)
        print(resel)
    
  3. Write your own capitalize function , Can change the first letter of the specified string into uppercase letter

       for example : 'abc' -> 'Abc'   '12asd'  --> '12asd'
    def capitalize1(str1:str):
        str2 = ''
        if 'a'<=str1[0]<='z':
            str2=chr(ord(str1[0])-32)+str1[1:]
            print(str2)
    
  4. Write your own endswith function , Determines whether a string has ended with the specified string

        for example :  character string 1:'abc231ab'  character string 2:'ab'  The result of the function is : True
             character string 1:'abc231ab'  character string 2:'ab1'  The result of the function is : False
    def endwith1(str1,str2):
        """ :param str1:  character string 1 :param str2:  End string  :return:None """
        if str1[-len(str2)]==str2:
            print(True)
        else:
            print(False)
        
    
  5. Write your own isdigit function , Determine whether a string is a pure numeric string

        for example : '1234921'   result : True
             '23 function '    result : False
             'a2390'     result : False
    def isdigtal1(str1):
        for i in str1:
            if i not in ['1','2','3','4','5','6','7','8','9','0']:
                print(False)
                break
        else:
            print(True)
    
  6. Write your own upper function , Change all lowercase letters in a string into uppercase letters

         for example : 'abH23 good rp1'    result : 'ABH23 good RP1'   
    def upper1(str1):
        str2 = ''
        for i in str1:
            if not 'a'<=i<='z':
                str2 += i
            else:
                str2 += chr(ord(i)-32)+str1[1:]
        print(str2)
    
  7. Write your own rjust function , Create a string whose length is the specified length , The original string is right justified in the new string , 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 str_fill(str1, int1, str2):
        a1 = len(str1)
        str3 = ''
        while int1 > a1:
            str3 += str2
            int1 -= 1
        result = str3 + str1
        return result
    
    
    result = str_fill('abc', 7, '^')
    print(result)
    
  8. Write your own index function , Counts all subscripts of the specified elements in the specified list , If no element is specified in the list, return -1

        for example :  list : [1, 2, 45, 'abc', 1, ' Hello ', 1, 0]   Elements : 1    result : 0,4,6  
             list : [' zhaoyun ', ' Guo Jia ', ' Zhugeliang ', ' Cao Cao ', ' zhaoyun ', ' king of Wu in the Three Kingdoms Era ']   Elements : ' zhaoyun '    result : 0,4
             list : [' zhaoyun ', ' Guo Jia ', ' Zhugeliang ', ' Cao Cao ', ' zhaoyun ', ' king of Wu in the Three Kingdoms Era ']   Elements : ' Guan yu '    result : -1     
    def index1(list1:list,element):
        if element in list1:
            for i in range(len(list1)):
                if list1[i] == element:
                    print(i)
        else:
            print('-1')
    
  9. Write your own len function , 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 len1(container):
        count = 0
        for i in container:
            count += 1
        print(count)
    
  10. Write your own max function , Gets the maximum value of the element 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 max1(order):
        list1 = []
        max2 = 0
        if type(order) == dict:
            for i in order:
                list1.append(order[i])
            order = list1
        for i in range(1,len(order)):
            if order[i-1]>order[i]:
                max2 = order[i-1]
            else:
                max2 = order[i]
        print(max2)
    
  11. Write a function to realize yourself in operation , Determine the number of... In the specified sequence , Whether the specified element exists

         for example :  Sequence : (12, 90, 'abc')    Elements : '90'      result : False
              Sequence : [12, 90, 'abc']    Elements : 90      result : True    
    def in1(order,element):
        for i in order:
            if element == i:
                print(True)
                break
        else:
            print(False)
    
    in1((10,90,'abc'),'90')
    
  12. Write your own replace function , Converts the old string specified in the specified string to 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 replace1(str1:str,old_str:str,new_str:str):
        str2 = ''
        i = 0
        while i < len(str1):
            if str1[i:i+len(old_str)] == old_str:
                i += len(old_str)
                str2 += new_str
            else:
                str2 += str1[i]
                i+=1
        print(str2)
    
原网站

版权声明
本文为[Soybeans are not soybeans]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011111319803.html