Day5 - 02 Definition Function of Python Study Notes

Defining functions Defining functions
    in Python requires the use of the def statement.
    Write the function name, parentheses, parameters in parentheses, and colons in turn, write the function body in an indented block, and return the function return value through the return statement. For example:
   
                    def my_abs(x):
                    if x >= 0:
                        return x
                    else:
                        return -x
                       
    Once return is executed, the function is executed. Even if the function does not use a return statement, the result will be returned after the function is executed, but the result is None.
    return None can be shortened to return.
            >>> def kk(x):
            ... if x == 0:
            ... return 'zero'
            ... elif x < 0:
            ... x = x + 1
            ... return x
            ... elif x > 0:
            ... return x - 100
            ...
            >>> kk(10)
            -90
            >>> kk(0)
            'zero'
            >>> kk(-100)
            -99
           
Call after function
    has been saved to file if defined The function definition is saved as a .py file (eg: aaa.py), then you can start the Python interpreter in the current directory of the file, and use from aaa import kk to import the kk() function stored in the aaa.py file , the filename does not contain the .py extension.
   
An empty function
    defines an empty function that does nothing. You can use a pass statement, such as:
        def nothing():
            pass An
empty function can be used as a placeholder. For example, in the program framework stage, the detailed code of the function may not be gone. Complete, you can write a pass statement first, so that the code framework can run. pass can also be used in other statements such as if.
Parameter checking
    Let’s compare the difference between the defined function and the built-in function:
        1. Define a function abs_own that evaluates the absolute value,
            def abs_own(x):
                if x > 0:
                    return x
                else:
                    return -x
        2. Now send an error to the function Parameters such as:
                >>> abs_own(5)
                5
                >>> abs_own(-5)
                5
                >>> abs_own('a')
                Traceback (most recent call last):
                  File "<stdin>", line 1, in < module>
                  File "<stdin>", line 2, in abs_own
                TypeError: unorderable types: str() > int()
               
        3. Send wrong parameters to the built-in absolute value function abs, such as:
                >>> abs(-5)
                5
                >>> abs('a')
                Traceback (most recent call last):
                File "<stdin>", line 1 , in <module>
                TypeError: bad operand type for abs(): 'str'
    By comparing the results of 2 and 3, the error message of the defined function is different from that of the built-in function. When the defined function encounters the wrong parameter data type, Couldn't do parameter checking for us.
   
The isinstance() data type check
    uses abs_own() as an example. It requires that the incoming parameter can only be an integer or a floating point number. If the parameter is invalid, an error message will be thrown:
        def abs_own(x):
            if not isinstance(x, ( int , float ) ):
                raise TypeError( 'bad operand type' )
            if x >= 0:


                return -x does
    wrong parameter passing again, the result is:
            >>> abs_own(5)
            5
            >>> abs_own(-5)
            5
            >>> abs_own('a')
            Traceback (most recent call last):
              File "<stdin >", line 1, in <module>
              File "<stdin>", line 3, in abs_own
            TypeError: bad operand type #The intended error message was thrown.
           
The function returns multiple values
    ​​In fact, the function returns a single value (actually a tuple), because the parentheses can be omitted when returning a tuple, so multiple variables can obtain the corresponding value according to the position by obtaining the position of the tuple element. .
   
   
Exercise: Define the function to solve the quadratic equation ax^2 + bx + c = 0
            import math
            def fangcheng(a,b,c):
                if not isinstance(a, (int,float) ):
                        raise TypeError(print(a,'must be a number'))
                if not isinstance(b, (int,float) ):
                        raise TypeError(print(b,'must be a number'))
                if not isinstance(c, (int,float)):
                        raise TypeError(print(c,'must be a number!'))
                if pow(b,2) - 4 * a * c < 0:
                        return('无解')
                else:
                        x = []
                        x.append(  ( -b + math.sqrt(pow(b,2) - 4 * a * c))     /    (2 * a)    )
                        x.append(  ( -b - math.sqrt(pow(b,2) - 4 * a * c))     /    (2 * a)    )
                        return x
            xi = int(input('1 number'))
            xii = int(input('2 number'))
            xiii = int(input('3 number'))
            print(fangcheng(xi,xii,xiii))
    #to abc There is actually a problem with the judgment of the value of . If b and c are 0, then this function will report an error.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325258317&siteId=291194637