Functions and types of function in Python

Functions in python:

  • Large programs are often difficult to manage, thus large programs are divided into smaller units known as functions.
  • It is simply a group of statements under any name i.e. function name and can be invoked (call) from another part of program.

Advantages of function:

Reduce the LOC:

  • As with function, the common set of code is written only once and can be called from any part of the program, so it reduces the Line of Code.

Easy updating:

  • If the function is not used then a set of code is to be repeated everywhere it is required.
  • Hence if we want to change in any formula or expression then we have to make changes to every place, if forgotten then the output will be not the desired output. With the function, we have to make changes to only one location.

Types of functions:

          1. Pre-defined functions

          2. Functions defined in modules using python libraries

          3. User-defined functions

          4. main() function

          5. Recursion Functions

          6. Lambda Functions

          7. Composition in functions

1. Pre-defined functions:

  • Python language provides built-in functions called Pre-defined function.
  • Python’s standard library is very extensive that offers many built-in functions that we can use without having to import any library.
  • The most widely used functions are

Example program:

  1. l=[8,6,1,5]

    print("List l=",l)

    print("The maximum value from this list is:",max(l))

    print("The minimum value from this list is:",min(l))

    print("The sum of value from this list is:",sum(l))

    print("The data type of l is:",type(l))

    print("The round of 7.13 of value is:",round(7.18,0))

    print("The power of 5 power 3 value is:",pow(5,3))

Output:

2. Functions defined in modules using Python libraries:

  • A Module is a file containing Python functions, variables, classes, and statements (.py file called modules).
  • The package is nothing but, it is a collections of modules stored in one folder called package or library.

Importing Python modules:

  1. To import entire module:

    Syntax:

              import <module name>

    Example:

              import math

    To import specific function from module:

    Syntax:

              from <module_name> import <function_name>

    Example:

              from math import sqrt

    Another way of importing entire module:

    Syntax:

              from <module_name> import *

    Example:

              from math import *

    Accessing function:

    Syntax:

              <module_name>.<function_name>

    Example:

              print(math.sqrt(5))

Example program using import:

  1. import math

    print("Squre root of 4 value:",math.sqrt(4))

    print("100 log10 value:",math.log10(100))

    print("sin 90 value:",math.sin(90))

    print("8 power of 3 value:",math.pow(8,3))

Output:

Example program uisng from module import*:

  1. from random import*

    print("Range from 1 to 6 of random value:",randrange(1,6))

    print ("List 1, 7, 3, 10, 4 of random value:",choice([1, 7, 3, 10, 4]))

Output:

3. User-defined functions:

  • The users have full scope to implement their own ideas in the function.
  • It defined by the users according to their requirements are called user-defined functions.
  • Elements of user-defined function:

               * Function definition
               * Function call or function

Rules:

  • Function name must be unique and follows naming rules the same as for identifiers.
  • A function can take arguments. It is optional.
  • An optional return statement to return a value from the function.
  • The function must be called/invoked to execute its code.

Syntax:

  1. def function_name(comma separated list of parameters):

              statements

    function_name(comma separated list of parameters)

Example program:

  1. def sum_two_num():#function definition

        print("Add of two number is : ",int(a)+int(b))

    a,b=input("Enter two values : ").split()

    sum_two_num()  #function calling

Output:

Parameters and Arguments in Function:

Parameters:

  • Parameters are the value(s) provided in the parenthesis when we
  • write function header. These are the values required by the function
  • to work.
  • The parameter is also known as formal arguments or formal parameter.

Arguments:

  • An Argument is a value that is passed to the function when it is called.
  •  In other words, arguments are the value(s) provided in the function call / invoke statement.
  • Arguments are also known as an actual argument or actual parameter.

Example program:

  1. def square(x):#formal argument

        print("Cube square value is :",x*x)

    a=int(input("Enter any vale for squre root: "))   

    square(a)#actual argument  

Output:

Note:

Where,

  • x is a Formal argument
  • a is Actual argument

Types of arguments:

There are 4 types of Actual Arguments allowed in Python:

1. Positional arguments

2. Default arguments

3. Keyword arguments

4. Variable length/arbitrary arguments

1. Positional arguments:

  1. def div(x,y):

        print("Divide of two numbers :",x/y)

    a=int(input("Enter first value: "))   

    b=int(input("Enter second value: "))

    div(a,b)    

Output:

2. Default arguments

  • Sometimes we can provide default values for our positional arguments. In this case, if we are not passing any value then default values will be considered.

  1. def sub(x=10,y=7):

        print("Subtraction of two value is : ",x-y)

    a=int(input("Enter firts number : "))

    b=int(input("Enter second number : "))

    sub(a,b)

    sub()#default value will return

Output:

3. Keyword(Named) Arguments:

  • The default keyword gives the flexibility to specify a default value for a parameter so that it can be skipped in the function call if needed. However, still, we cannot change the order of arguments in function call i.e. you have to remember the order of the arguments and pass the value accordingly.
  • To get control and flexibility over the values sent as arguments, python offers keyword arguments.
  • This allows calling a function with arguments in any order using the name of the arguments.

Rules for combining all three type of arguments:

  • An argument list must first contain positional arguments followed by keyword arguments.
  • Keyword arguments should be taken from the required arguments.
  • You cannot specify a value for an argument more than once.
  • Default arguments must not be followed by non-default arguments.

Example program:

  1. def mul(x,y=2,z=3):

        print("Multiplying of three numbers:",x*y*z)

    mul(2)

    mul(7,y=3,z=1)

Output:

4. Variable length/arbitrary arguments:

Special Symbols Used for passing arguments:-

1.)*args (Non-Keyword Arguments):

  • *args is used to pass the number of argument based on your values.

Example program:

  1. def sum(*num):

        result = 0

        for i in num:

            result = result + i

        return result

    print(sum(1, 2))        

    print(sum(1, 2, 3))    

    print(sum(5, 2, 3, 4))

Output:

2.)**kwargs (Keyword Arguments):

Using dictionary:

  1. def std(**data):

        for key, value in data.items():

            print(key," \t: ",value)

    std(Roll=4217, Name="Kurshitha", Age=22, Mark=432)

Output:

Using normal variables:

  1. def fun(**name):

      print("My name is " + name["fname"]+" "+name["lname"])

    fun(fname = "Kurshitha", lname = "Sulaiman")

Output:

Number of ways to give user-defined functions:

1. Function with no arguments and no return statement

2. Function with no argument but return value

3. Function with arguments but no return value

4. Function with arguments and return value

1. Function with no arguments and no return:

  1. def sum_two_num():#function definition

        print("Add of two number is : ",int(a)+int(b))

    a,b=input("Enter two values : ").split()

    sum_two_num()  #function calling

Output:

2. Function with no argument but return value:

  1. def sum_two_num():

        return (print("Add of two value is: ",int(a)+int(b)))

    a,b=input("Enter two values : ").split()

    sum_two_num()

Output:

3. Function with arguments but no return value

  1. def sum_two_num(x,y):

        print("Add of two number is : ",x+y)

    a,b=input("Enter two values : ").split()

    sum_two_num(int(a),int(b))    

Output:

4. Function with arguments and return value:

  • We can return values from function using return keyword.
  • The return value must be used at the calling place by

*Use with print()

*Use in any expression

*Either store it any variable

(i) Use with print():

  1. def sum_two_num(x,y):

        return x+y

    a,b=input("Enter two values : ").split()

    print("Add of two number is : ",sum_two_num(int(a),int(b)))#return in print()

Output:

(ii) Use in any expression:

  1. def sum_two_num(x,y):

        z=x+y#Within function also have expression

        return z

    a,b=input("Enter two values : ").split()

    print("Add of two number is : ", sum_two_num(int(a),int(b)))

Output:

(iii) Store it any variable:

  1. def sum_two_num(x,y):

        return x+y

    a,b=input("Enter two values : ").split()

    c=sum_two_num(int(a),int(b))#return value is stored in variable

    print("Add of two number is : ",c)

Output:

Returning multiple values:

  • Unlike other programming languages, python lets you return more than one value from function.
  • The multiple return values must be either stored in TUPLE or we can UNPACK the received value by specifying the same number of variables on the left of the assignment of the function call.

Multiple return value stored in TUPLE:

  1. def add_10(x,y,z):

        return x+10,y+10,z+10

    a=int(input("Enter first number : "))

    b=int(input("Enter second number : "))

    c=int(input("Enter third number : "))

    result=add_10(a,b,c)

    print(result)

Output:

Multiple return values stored by unpacking in multiple variables:

  1. def add_10(x,y,z):

        return x+10,y+10,z+10

    a=int(input("Enter first number : "))

    b=int(input("Enter second number : "))

    c=int(input("Enter third number : "))

    a,b,c=add_10(a,b,c)

    print(a)

    print(b)

    print(c)

Output:

4. main() function:

  • By default, every program starts its execution from the main() function. In Python including a main() function is not mandatory.
  • It can structure our Python in a logical way that puts components of the program the most in one program's important function.
  • We can get the name of the current module executing by using the built-in variable name (2 underscores before and after of name).
  • Most non-python programmers are having the habit of writing a main()function where the important and starter code of programs are written.
  • In Python, we can also create main() and call it by checking name to main and then call any function, in this case main().

Example program:

  1. def area(length,breadth):

        return length*breadth

    def main():

        l=int(input("Enter length: "))

        b=int(input("Enter length: "))

        a=area(l,b)

        print("Area of rectangle = ",a)

    if __name__=='__main__':

        main()

        print("__name__ name of value is : ",__name__)

Output:

5. Recursion function:

  • It is one of the most powerful tools in programming language.
  • It is a process where function calls itself again and again.
  • Recursion basically divides the big problem into small problems up to the point where it can be solved easily.

Condition for Implementing Recursion:

  • It must contain base condition i.e. at which point recursion will end Otherwise it will become infinite.
  • It takes more memory as compare to LOOP statement because with every recursion call memory space is allocated for local variables.
  • It is less efficient in terms of speed and execution time
  • Suitable for complex data structure problems like TREE, GRAPH, etc

Example program:

  1. def factorial(num):

        if num==1:

            return 1

        else:

            return num*factorial(num-1)

    n=int(input("Enter any number : "))

    fact=factorial(n)

    print("Factorial of ",n," is ",fact)

Output:

6. Anonymous Functions:

  • In Python, an anonymous function is a function that is defined without a name
  • While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword
  • Hence, anonymous functions are also called as lambda functions.

Use of lambda or anonymous function:

  • Lambda function is mostly used for creating small and one-time anonymous functions. That means, Lambda function can take any number of arguments and must return one value in the form of an expression
  • Lambda functions are mainly used in combination with the functions like filter(), map() and reduce().

Syntax:

  1. Variable=lambda [argument(s)] :expression

Example program:

  1. sum = lambda val1, val2: val1 + val2

    print ('The Sum is :', sum(20,40))

    print ('The Sum is :', sum(-10,40))

Output:

7. Composition in functions:

  • The composition function is used to execute expression and get an expression from the user.
  • Using eval() function and full form evaluate value through function. 
  • The value returned by a function may be used as an argument for another function in a nested manner. This is called composition.
  • For example, if we wish to take a numeric value or an expression as an input from the user, we take the input string from the user using the function input() and apply eval() function to evaluate its value.

Example program for print the set of elements:

  1. result=eval(input("Enter arithmetic operation: "))

    print(result)

Output:

Share:

No comments:

Post a Comment

Popular Posts

Search This Blog

Powered by Blogger.

Service Support

Need our help to Learn or Post New Concepts Contact me

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me