Functions - Python

  • dir(varName) => Returns list of all methods that can be used
    • Including dunder methods
  • Define and Call a function
        def functionName(arguments):
            # statements
        functionName(parameters)
    
  • Returning a value
        def functionName(arguments):
            # statements
            return value
        varName = functionName(parameters)
    
  • Doesn't gives error for unfinished function
        def functionName(arguments):
            pass
    
  • Default Arguments
        def functionName(varName1=value1, varName2=value2):
            # statements
        functionName() # Default values will be used
        functionName(varName2=value3) # Passing value by argument name
        functionName(varName2=value3, varName1=value4) # Order doesn't matter
    
  • Argument as Tuple
        def functionName(*varName):
            # statements
        functionName(value1, value2)
    
  • Argument as Dictionary
        def functionName(**varName):
            # statements
        functionName(key1="value1", key2="value2")
    
  • Docstring => For mentioning function description
        def functionName():
            '''value'''
            # statements
        print(functionName.__doc__) # Prints Docstring
        print(functionName?) # Prints Docstring
    
  • Recursion => Calling same function inside a function
        def functionName(arguments):
            # statements
            functionName(parameters)
            # statements
        functionName(parameters)
    
  • Function runs only when original script is running directly and not when it is when imported
        def functionName():
            # statements
        if __name__ == "__main__":
            functionName()
    
  • Lambda Function => Small anonymous function without a name, Returns the value, Used as arguments to higher-order function
        functionName = lambda arguments: statement
        functionName = lambda argument1, argument2: statement
        varName = functionName(parameters)
    
  • Decorator => Tool that allows you to modify the behavior of function and methods, Used to add functionality like logging, memoization, access control
        def functionName1(fx):
            def mfx(*args, **kwargs):
                # Statements
                fx(*args, **kwargs)
                # Statements
            return mfx
        @functionName1
        def functionName(arguments):
            # Statements
        functionName(parameters)
        # OR
        functionName1(functionName)(parameters) # @ is not required
    
Share: