In Python def keyword is used to define function . It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented.

  • Syntax to define functions

    def function_name(parameter):
                     function body
                     ......................
                    .......................

    Example)
    drag_handle
     
    # creating function
    def square(n):
        print(n * n)
    
    
    # function ended
    # now call the function
    square(5)
    square(10)
    square(15)
    square(20)
    
    Output:
    25
    100
    225
    400
    

    function to print Fibonacci series up to n

    # function to  print Fibonacci series up to n
    def printFebnocci(n):
        a, b = 0, 1
        while a < n:
            print(a, end=' ')
            a, b = b, a + b
    
    
    print()
    
    printFebnocci(2000)
    

    Output:
    0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 
  • Default Argument Values in function

    We can specify the default value of the variable passed in function argument . These values are used when we do not pass any value while calling the function . for example

    Example)
    drag_handle
     
    def test(name='Raman'):
        print(name)
    
    
    # now calling the function
    test()
    test("John")
    
    Output:
    Raman
    John
    
  • Function using Lambda Expressions

    Small anonymous functions can be created with the lambda keyword . These anonymous function is a function without having any name. These function is used with reference of the function. for example

    Example)
    drag_handle
     
    # defining the function using lambda expression
    # storing the reference of it in f variable
    f = lambda a, b: a + b
    
    # now calling the function
    print(f(4,5))
    print(f(30,5))
    print(f(9,5))
    Output:
    9
    35
    14
    

    Example of lambda

    def increment(n):
        return lambda x: x + n
    
    
    # use the above function
    f = increment(45)
    print(f(2))
    print(f(5))
    print(f(2))
    

    Output:
    47
    50
    47
    

What next?

The next topic is Python if Statement

Share this page