ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] - Function , Lambda
    개발/Python 2022. 7. 27. 14:37

    1. Function


    A function is a block of code which only runs when it is called.
    You can pass data, known as parameters, into a function.
    A function can return data as a result.
    # create function
    def test():
      return "test"
      
    # call function
    test()

     

    1-1) *args Argument

    If you do not know how many arguments that will be passed into your function, add a '*' before the parameter name in the function definition
    def my_test(*test_data):
        print("test {}".format(test_data[2]) )
        
    my_test("12", "34", "56")
    > test56

     

    1-2) **kwargs Arguement

    If you do not know how many keyword arguments that will be passed into your function, add two asterisk: '**'
     before the parameter name in the function definition.
    def my_function(**test_data):
      print("test result {} ".format(test_data["test1"]))
    
    my_function(test1 = "12", test2 = "34")

     

    1-3) Default Parameter

    def my_function(country = "Norway"):
      print("I am from {}".format(country) )
      
     my_function("Korea")

     

    1-4) pass statement

    function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.
    def myfunction():
      pass

     

    2. Lambda


    A lambda function is a small anonymous function.

    Syntax

    lambda arguments : expression
    # lambda example
    x = lambda a : a + 10
    
    # lambda function
    def myfunc(n):
      return lambda a : a * n
      
    mydoubler = myfunc(2)
    mytripler = myfunc(3)
    
    print(mydoubler(11))
    > 22
    
    print(mytripler(11))
    > 33

    '개발 > Python' 카테고리의 다른 글

    [Python] - Sort / Reverse  (0) 2022.07.27
    [Python] - Iterators  (0) 2022.07.27
    [Python] - Powerful Function  (0) 2022.07.27
    [Python] - Set  (0) 2022.07.27
    [Python] - Dictionary  (0) 2022.07.27

    댓글

Designed by Tistory.