Posts

11 conditional operations in python

 1. Using if, elif and else we can perform conditional operations 2. Using conditioanl operations we can execute a block of code based on condition # Below are the python operators to perform conditional operations     1. Arthmetic operators(+,-,*,%,/,//)         1. Uesd to do addition and substraction operations     2. Assignment operators(=,+=,-=,*=,%=,/+,//+)         1. Used to assign value to variable     3. Comparison operators(==,!=,>,>=,<,<=)         1. These operators compare the values on either sides of them and decide the relation among them.              They are also called Relational operators.     4. Logical operators(and,or,not)         1. Using logical operations we can execute a block of code based on multiple condition.     5. Membership operators(in,not in)         1. ...

12 Loop statements in python

 1. Using loops we can execute a block of code repeatedly 2. Python support 3 types of loops     1. For loop    ==> for loop Iterate based on range     2. While loop  ==> while loop Iterate based on condition     3. nested loop ==> If a loop contains another loop that is called nested loop 3. Loop statements      1. break     ==> break used to terminates the loop     2. continue  ==> continue used to skip the current iteration      3. pass      ==>          1. pass will do nothing          2. we use pass when statement is require to aviod syntax issues. 1) for loop with range ''' 1. Range() function used to craete a range of values ''' #for n in range(8):        # 0 to n-1  #  print(n) #for n in range(3, 8):     # n to n-1  #   print(n) #...

13 command line parameters in python

 ''' 1. You can access to the command line parameters using the sys.argv   Example ::- command_line_argu.py "uma mahesh" 78 ''' import sys ## To get first command line argument print(' argv[1] :: ' , sys.argv[1]) ## To get second command line argument print(' argv[2] :: ' , sys.argv[2]) ## To get file name with full path #print(' argv[0] :: ' , sys.argv[0]) ## To get all command line argument with file name #print(' argv :: ' , sys.argv)

49 decorators in python

 ''' 1. used to modify the behaviour of function or class. Using decorators we can change a behaiviar of function  without changing any fucntion code. 2. using @ we can assign decorator to the function ## How to create decorator Decorator fucntion takes one argument as function Decorator function contains another wrapper function Inside wrapper function only we have to call function argument Decorator function will return wrapper function # Decorator are used to create the static method class One():     @staticmethod     def add():         print(' \n Static Method') #ins = One() #ins.add() One.add() #Using @classmethod decorator we can create Class method. class One():     name = 'umamahesh'     @classmethod     def sub(cls, n):         print(' \n id of One : ', id(One))         print(' \n id of cls : ', id(cls))         cls.name = n     ...

48 generator in python

  ''' 1. Using generator we can execute a block of code  based on demand by using next() function. 2. using yield keyword we can create a generator. ''' def gen_fun(n):     for i in range(n):         print('Before yield')         yield i         print('After yield') gen_obj = gen_fun(10) #print(next(gen_obj)) #print(next(gen_obj)) # print(next(gen_obj)) ## Iterate based on for loop #for i in gen_obj: #    print(' For Loop ', i) def gen_fun(n):         print('Before return')         yield n         print(' \n After return')         yield n gen_obj = gen_fun(10) print(next(gen_obj)) print(next(gen_obj))

47 iterator in python

 ''' 1. using iterators we can get sequence of values  based on demand by using next() function. 2. We can create iterators by using iter() function. ''' l = [1,2,3,4,5] #for i in l: #    print(i) #iterator creation l = [1,2,3,4,5] iter_obj = iter(l) print(next(iter_obj)) print(next(iter_obj)) for i in iter_obj:     print(' For loop ', i) #print(next(iter_obj)) # # #

14 List comprehensions in python

  ''' List comprehensions are used for creating new list from another iterables. Using list comprehensions we can do loop operations inside a square brackets. ''' l = [1, 2, 3, 4] ## Basic list comprehension #r = [ n + 10 for n in l] #print(r) ## list comprehension with if condition #r = [n + 2 for n in l if n > 2] #print(r) ## list comprehension with if and else condition r = [n + 100 if n > 2 else n + 10 for n in l] print(r)

46 reduce function in python

 ''' 1. reduce is used to do operation on each iterable value and  its return all operations result sum. 2. reduce takes two parameters one is function another one is iterable object ''' from functools import reduce #(1+2)+3)+4)+5) #fact = reduce(lambda a,b: a * b,[1,2,3,4,5]) fib = reduce(lambda a,b: a + b,[1,2,3,4,5]) print(fib)

45 filter() method in python

  ''' 1. The filter() method filters the given sequence with the help of a function and  retun filter object. 2. filter taks two parameters one is function another one is iterable object ''' Use lambda function with filter() The Python built-in filter() function accepts a function and a list as an argument.  It provides an effective way to filter out all elements of the sequence.  It returns the new sequence in which the function evaluates to True. ## Filter with lambda function fo = filter(lambda a: a % 2 == 0 ,[1,2,6,4,5]) print(list(fo)) #program to filter out the tuple which contains odd numbers     lst = (10,22,37,41,100,123,29)   oddlist = tuple(filter(lambda x:(x%3 == 0),lst)) # the tuple contains all the items of the tuple for which the lambda function evaluates to true     print(oddlist)  

44 map function in python

  ''' 1. map is used to do operation on each iterable value and  it will return all operations result in map object foramt. 2. Map takes two parameters one is function  another one is iterable object ''' ## Map with def fucntion def add(a):     return  a + 10 #mo = map(add, (1,2,3,4,5,6)) #print(list(mo)) ## Map with lambda function #mo = map(lambda a, b: a + b ,[1,2,3,4,5,6], [11,22,33,44]) #print(tuple(mo))

43 Lambda function in Python

  ''' 1. Lambda is a another way to create a function. 2. Lambda is a one line anonymous function it doesn't contains name. 3. Using lambda we can do only one expression. ''' ## Lambda with out arguments #add = lambda : 3 + 5 #r = add() #print(r) ## Lambda with arguments  #add = lambda a,b: a + b #r = add(2, 33) #print(r) ## Lambda with if and else add = lambda a,b: a + 10 if a > 5 else b + 100 print(add(6,6)) ------lambda with Map----- # Double the value of each element myList = [10, 25, 17, 9, 30, -5] myList2 = map(lambda n : n*2, myList) print myList2 ------lambda with filter------ # Filters the elements which are even numbers myList = [10, 25, 17, 9, 30, -5] myList2 = list(filter(lambda n : (n%2 == 0), myList)) print(myList2) ------Use lambda function with filter()----- The Python built-in filter() function accepts a function and a list as an argument.  It provides an effective way to filter out all elements of the sequence.  It returns the new sequen...

42 standard input in python

 ''' 1. Using standard input we can get values at run time. 2. using input() function we can get run time values in python. ''' uname = input('\n Please enter your name ::') print(' \n UNAME IS : ', uname) #========== pin   = input('\n Please enter PIN   ::') print(' \n PIN   IS : ', pin)

41 Encapsulation in python

  ''' 1. Encapsulation is the process of wrapping up variables and methods into  a single entity. In programming, a class is an example  that wraps all the variables and methods defined inside it. class One():     name = 'umamahesh'     def add(self):         print(' ADD is ')     def sub(self):         print(' SUB is:') ins = One() print('\n ', ins.name) --Using encapsulation we can give protection to the class members.  It can achieve Using access modifiers. Encapsulation can be achieved using Private and Protected Access Members. ''' Example---CSE department faculty cannot access the ECE department student record and  so on. Here, the department acts as the class and  student records act like variables and methods. =======Why Do We Need Encapsulation?=========== ===Encapsulation acts as a protective layer by ensuring that,  access to wrapped data is not possible by any code define...

40 Access modifiers in python

 ''' 1. All name variables and methods are public by default in Python 2. Protected variable we can define By prefixing the name of your variable or  method with a single underscore.  Protected mean you’re telling others “don’t touch this, unless you’re a subclass” 3. private variable we can define By prefixing  the name of your variable with a double underscore, By declaring your data member private you mean,  that nobody should be able to access it from outside the class. ''' class One():     name   = ' public '     # public     _name  = ' protect '    # protect     __name = ' Pravate '    # pravate     def sum(self):         #self.__sub()         print(' \n Public ' )     def _add(self):         print(' \n Protect ' )     def __sub(self):         print(' \n Pravate ') ins ...

39 abstract method in python

  ''' 1. An abstract method is a method that is declared, but contains no implementation. 2. By defining an abstract base class,  you can define a common API for a set of subclasses. 3. By using abc module we can define abstract class. ''' from abc import ABCMeta,abstractmethod class One(metaclass=ABCMeta):     @abstractmethod     def add(self):         print(' \n ONE ADD ')     @abstractmethod     def sub(self):         pass #a = One() #a.add() ## If you inheritence an abstaruact class  you should impliment that all those methods which are abstract ,methods class Two(One):     def add(self):         print(" \n TWO ADD")     def sub(self):         print(' \n TWO SUB') ins = Two() ins.add() ins.sub()

38 overriding in python

  ''' 1. If you have same method names in class A and class B,  then if you Inheritence class A into class B  then Class A method will override with class B method. ''' class A():     def add(self):         print('\n A ADD ') class B():     def add(self):         print('\n B ADD ') class C(B, A):     def add(self):         print(' \n C ADD ') inst = C() inst.add()

37 polymorphism in python

  ''' 1. An object behavior will get change during run time. 2. By using inheritence and overriding we can achive it. ''' class Car:     def colour(self):         print('red')     def music_system(self):         print('philips')     def airbags(self):         print(4) class Swift(Car):     def colour(self):         print('white') class Varna(Car):     def colour(self):         print('block')     def music_system(self):         print('sony')     def airbags(self):         print(6) car_ins = Car() swift_ins = Swift() varna_ins = Varna() car_ins.colour() swift_ins.colour() varna_ins.colour()

36 Multi Level inheritance in python

 ''' 1. We can inherit a derived class from another derived class,  this process is known as multilevel inheritance 2. Example :- We have three classes A, B and C,  If you inheritance class A into class B and class B into class C This is called  Multi Level inheritance. ''' class A():     def add(self, a, b):         print('sum is', a + b)     def sub(self, a, b):         print('sub is', a - b) class B(A):     def colour(self):         print('Blue') class C(B):     pass ins = C() print(dir(ins)) #ins.colour()

35 inheritance in python

  ''' 1. If you inheritance more than one class that is called multi inheritance ''' class One():     name = 'umamahesh'     def add(self, a, b):         print('sum is', a + b)     def sub(self, a, b):         print('sub is', a - b) class Two():     def colour(self):         print('Blue') class Three(One,Two):     pass ins = Three() #print(dir(ins)) ins.colour() ins.add(5,6)

34 class method

 ''' 1. Using @classmethod decorator we can create Class method. 2. For class method we have to give cls argument. 3. Using classmethod we can change class attributes. 4. classmethod we can call through instance or without intance. ''' class One():     name = 'umamahesh'     @classmethod     def sub(cls, n):         print(' \n id of One : ', id(One))         print(' \n id of cls : ', id(cls))         cls.name = n         print(' \n class variable is :: ', One.name) #ins = One() #ins.sub('kumar') One.sub('Nagesh')