Function

作者: bin_guo | 来源:发表于2018-09-10 11:44 被阅读0次

    In this article, just introducing the basic knowledge of function, for more information, please check Python--Middle.

    Function (Method)

    In general, Function also is called Method in sometimes. It is the smallest algorithm logic unit. In short, Function is like a black box, the only thing you need to do for using it is passing in the inputs with the correct signature, and it can return the result which you expected. When you are programming, you'd better separate your logic into different pieces, then it will be tested easier.

    Calling function
    If the function you are calling is a built-in function, then you can directly use it. But if the function is coming from a third package. Then you need to import the package, and calling it directly. If the function is coming from the third package and you have imported it, the name of function also same to the built-in function, you need to explicitly give the prefix for the third party function.
    example

    //Code==========
    #abs function
    print(abs(100))
    #int function
    print(int('123'))
    print(int(12.34))
    #str function
    print(str(123))
    //Result==========
    100
    123
    12
    123
    

    Define a function
    It doesn't like other oop languages when you want to define a function in Python, you need to explicitly have a keyword def, then the name of the function and the parameters follow up. Next line will be the body of the function. For the return value, if there is None to return, you can write return and no value follows up.
    example

    //Code==========
    def square_of_sum(L):
        sum = 0
        for item in L:
            sum += item*item
        return sum
    print (square_of_sum([1, 2, 3, 4, 5]))
    print (square_of_sum([-5, 0, 5, 15, 25]))
    //Result==========
    55
    900
    

    Multi-return-value
    Actually Python only can return a single value, but how it returned multiple values? The answer is tuple, it combimes all values together into a tuple.
    Let's have an example, says there is a person who wants to walk from a point to another point. Given start point coordinate, steps, and angle [input]. You need to calculate the coordinate of the end point [output]. (math package provided sin and cos functions, so that you can directly use them after imported the package)

    //Code==========
    import math
    def move(x, y, step, angle):
        nx = x + step * math.cos(angle)
        ny = y - step * math.sin(angle)
        return nx, ny
    x, y = move(100, 100, 60, math.pi / 6)
    print(x, y)
    //Result==========
    151.96152422706632 70.0
    

    example(calculate a binary linear equation, ax² + bx + c = 0)

    //Code==========
    import math
    def quadratic_equation(a, b, c):
        return ((-b)+math.sqrt(b*b-4*a*c))/(2*a), ((-b)-math.sqrt(b*b-4*a*c))/(2*a)
    print (quadratic_equation(2, 3, 0))
    print (quadratic_equation(1, -6, 5))
    //Result==========
    (0.0, -1.5)
    (5.0, 1.0)
    

    Recursive Function (It's my pain..)
    In short, it is a function by using itself until there is a break condition be triggered. For example, n!, it is equals n! = 1 * 2 * 3 * ... * (n-1) * n, and finally fact(n) = fact(n-1) * n when n == 1, it will be break.

    def fact(n):
        if n==1:
            return 1
        return n * fact(n - 1)
    

    if we pass n = 5, then

    ===> fact(5)
    ===> 5 * fact(4)
    ===> 5 * (4 * fact(3))
    ===> 5 * (4 * (3 * fact(2)))
    ===> 5 * (4 * (3 * (2 * fact(1))))
    ===> 5 * (4 * (3 * (2 * 1)))
    ===> 5 * (4 * (3 * 2))
    ===> 5 * (4 * 6)
    ===> 5 * 24
    ===> 120
    

    example(Hanno Tower Game)

    Hanno Tower (5-layer)
    //Code==========
    def move(n, a, b, c):
        if n==1:
            print (a,'-->',c) 
        else:
            move(n-1, a, c, b)
            print (a, '-->', c, ',')
            move(n-1, b, a, c)
    move(4, 'A', 'B', 'C')
    //Result==========
    A --> B, A --> C, B --> C, A --> B, C --> A, C --> B, A --> B,
    A --> C, B --> C, B --> A, C --> A, B --> C, A --> B, A --> C,
    B --> C
    

    Function's parameter with default value
    Sometimes, people using function with optional parameter, but in your function body still need this parameter to join the calculation, at this time, you can have a default value for the parameter, and no matter pass in or not, make sure that the parameter still has value.
    example

    //Code==========
    def greet(string='world'):
        print ('hello,', string)
    greet()
    greet('Bart')
    //Result==========
    hello, world
    hello, Bart
    

    The amount of parameters are dynamic
    This is more flexable for using it. you can pass 0 or more than 1 parameters when you using this method. Python combines all parameters as a tuple, so that when you define your function, you can think the collection actually is a tuple.
    example(calculate average)

    //Code==========
    def average(*args):
        sum = 0.0
        if len(args) == 0:
            return 0.0
        else: 
            for item in args:
                sum += item
            return sum/len(args)
    print (average())
    print (average(1, 2))
    print (average(1, 2, 2, 3, 4))
    //Result==========
    0.0
    1.5
    2.4
    

    相关文章

      网友评论

          本文标题:Function

          本文链接:https://www.haomeiwen.com/subject/cnfsgftx.html