Python3 Types of functions

Python  Functions

Types of Functions:

       1.  Built-in Functions
       2.  User-defined Functions

 Built-in Functions :

1 . abs()

       #find the absolute value
       num=-100
       print(abs(num))
 
output: 100

2 . all()

  #return value of all() function
  True : if all elements in an iterable are true
  False : if any element in an iterable is false

Eg:
       lst=[1,2,3,4]
       print(all(lst))
      
       lst1=[0,2,3,4]
       print(all(lst1))

output: True
              False
  
       lst=[ ]
       print(all(lst))
  
       lst1=[False,1,2]     #False present in a list, then all(lst) is also False
       print(all(lst1))

output:  True
               False

 3 . dir()

  The dir() tries to return a list of valid attributes of the object.

  If the object has dir() method, the method will be called and must return the list of attributes.

  If the object doesn't have dir() method, the method tries to find information from the dict attribute (if defined) ,and from type object. In this case, the list returned from dir() may not be complete.

Eg:
       nums=[1,2,3]
       print(dir(nums))

Output :

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__','__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__','__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__','__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__','__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__','__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear','copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

4 . divmod()

     The divmod() method takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder. 

Eg:
       print(divmod(9,2)   #print quotient and remainder of a tuple 

output:  (4,1)

 5 . enumerate()

    The enumerate() (meaning to list) method counter to an iterable and return it

   syntax: 

              enumerate(iterable, start=0)

 

Eg:       
       nums=[10,20,30,40]
       for index, num in enumerate(nums): 
             print("index {0} has value {1}".format(index,num))

output: index 0 has value 10
             index 1 has value 20
             index 2 has value 30
             index 3 has value 40

6 . filter()

            The filter() method constructs an iterator from elements of an iterable for which a function returns true.
  
Syntax: 

             filter(function,iterable)

Eg:
       def find_positive_number(num):
             """
             This function returns the positive number if num is position
             """
             if num>0:
                  return num

       number_list=range(-10,10)
       print(list(number_list))
       positive_num_lst=list(filter(find_positive_number,number_list))
       print(positive_num_lst)

Output:   [-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9]
                 [1,2,3,4,5,6,7,8,9]
 
 7 . isinstance()

         The isinstance() function checks if the object (first argument) is ann instance or subclass of classinfo class(second argument).

   Syntax:
   
            isinstance(object,classinfo)

 

Eg:
       lst=[1,2,3,4]
       print(isinstance(lst,list))

       t=(1,2,3,4)
       print(isinstance(t,list))

output:  True
               False

8 . map()

        Map applies a function to all the items in an input_list.

 Syntax: 
   
           map(function_to_apply,list_of_inputs)

 Eg: 

       #normal method
       nums=[1,2,3,4]
 
       square=[ ]
       for num in nums:
             square.append(num**2)

       print(square)

output:  [1,4,9,16]

       #using map() function
       nums=[1,2,3,4]

       def poweroftwo(num):
             return num**2

       squared=list(map(poweroftwo,nums))
       print(squared)

output: [1,4,9,16]

9 .  reduce()

               reduce()function is for performing some computation on a list and returning the result.
 
   It applies a rolling computational to sequential pairs of values in a list.

  Eg:     
       #product of elements in a list using normal method.
       product=1
       lst=[1,2,3,4]
        for num in lst:
              product*=num

       print(product)

output: 24

       #product of elements in a list using reduce() method
       lst=[1,2,3,4]
       from functools import reduce
      
       def multiply(x,y):
             return x*y;

       product=reduce(multiply, lst)
       print(product)

output: 24

  *map() and filter() function applies to each element individually in a list whereas reduce() function applies to one element to another element consecutively(sequential).

User-defined Functions

   Functions that we define ourselves to do certain specific task are referred as user_defined functions

   If we use functions written by others in the form of library, it can be termed as library functions.

 Advantages

  1. User-defined functions help to decompose a large program into smaller segments which makes program easy to understand, maintain and debug.
  2. If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function.
  3. Programmers working on large project can divide the workload by making different functions.

 Example: 
  
       def product_numbers(a,b):
             return a*b

       num1=10;num2=20
       print("product of {0} and {1} is {2}".format(num1,num2,product_numbers(num1,num2))

output:  product of 10 and 20 is 200

Python  Program to make a simple calculator that can add, subtract, multiply and division

       def add(a,b):
             return a+b

       def subtract(a,b):
             return a-b

       def multiply(a,b):
              return a*b
 
       def division(a,b):
              return a/b

       print("Select option: ")  
       print("1.Addition")
       print("2.Subtraction")
       print("3.Multiplication")
       print("4.Division")   

       choice=int(input("Enter a choice: "))
       num1=float(input("first number: "))
       num2=float(input("second number: ")
       if choice==1:
            print("Addition of {0} and {1} is: {2} ".format(num1,num2,add(num1,num2)))
       elif choice==2:
            print("Subtraction of {0} and {1} is: {2}".format(num1,num2,subtract(num1,num2)))
       elif choice==3:
            print("Multiplication of {0} and {1} is: {2}".format(num1,num2,multiply(num1,num2)))
       elif choice==4:
            print("Division of {0} and {1} is: {2}".format(num1,num2,division(num1,num2)))
       else:
            print("invalid choice")


output:   Select option:
               1.Addition
               2.Subtraction
               3.Multiplication
               4.Division
               Enter a choice:3
               12.2
               2.3
              Subtraction of 12 and 3.5 is: 28.059999999999995










Comments

Popular posts from this blog

Python3

Python3 Function Arguments

Python3 File Handling