Posts

Showing posts from September, 2023

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. Using member ship operations we can find a value in list and sub string in a string     6. Identity operators(is,is not)         1. Using identity operators we can check memory location of

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) #for n in range(8, 15, 3):  # n to n-1 , step #    print(n) for n in range(5, 8):     print(n)  #for i in range(4, 8): #    print(i) #    if i > 4 : break #for i in range(4):     # if i : continue     # print

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         print(' \n class variable is :: ', One.name) #ins = One() #ins.sub('kumar') One.sub(&#

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 defined outside the class  in which the wrapped data a

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 = One() ins.sum() #print(' \n ', ins.__name)

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')

33 static method in python

  ''' 1. Using @staticmethod decorator we can create static method. 2. For Static method self argument doesn't required. 3. Using staticmethod we can provide same behavior to the all the instances of class. 4. staticmethod we can call through instance or without intance. ''' class One():     @staticmethod     def add():         print(' \n Static Method') #ins = One() #ins.add() One.add()

32 constructor in python

  ## Using __init__ we can create constructor ## Using constructor we can create instance varables. ## Constructor method will call when calling class class One:     def __init__(self, name, eid):         self.name = name         self.eid  = eid         print('__init__')     def add(self):         print(' Add ', self.name)     def sub(self):         print(' SUB ', self.name)         print(' SUB EID ', self.eid) inst = One('UMAMAHESH', 999) #inst.add() #inst.sub()

31 Self keyword in python

  ''' 1. self is used to refer the instance of the class to the method. 2. Based on self only the method will get to know for which instace it has to responce. 3. We can give any name in place of self. ''' class One():     def sub(self, a, b):         #print(' \n ID of self is : ', id())         print(' \n A value is :', a)         print(' \n A value is :', b) ins1 = One() ins2 = One() print(' \n ID of ins1 is  : ', id(ins1)) ins1.sub(10,5) #ins2.sub(100,200)

30 class in python

  # Craete a class with varable amd methods class One():     name = 'umamahesh'     def add(self):         print(' addition is :', 5 + 7)     def sum(self, a, b):         return a + b # To create a instance to the class inst = One() # To print class variable name print(' Name is :', inst.name) # To call add method inst.add() # To call sum method r = inst.sum(4,6) print(' Sum is :', r)

29 exception in python

  1. An exception is an event, which occurs during the execution of a program. 2. Using try,except,else and finally block we can handle exception. 3. Using exceptions we can handle run time errors. # else 1. else block will execute when the try block executed successfully with out any errors. # Finally *** 1. finally block will execute both times when try block executed successfully or fail. 2. It is used to do the cleanup process. 1) try and except  import sys d = {'A':1,'B':2} try:     d['C']     'we' + '123'     sys.ok()     import re     open('2_else.py') except ModuleNotFoundError:     print(' Module is not defined ') except NameError:     print(' name is not defined please define ') except KeyError:     print(' KeyError ') except FileNotFoundError as e:     print(' Please define file ', e) except:     print(' Try block got failed ') 2)else block #''' #1. else block will execute whe

28 packages in python

  1. A package is basically a directory with Python files. 2. Using __init__.py file  we put several modules from different paths into a Package. # To import all attrbutes from one package from one import * ## To print name which exist in  windows module print(windows.name) ## To call os function which exsit in  mac module os() ## To call vmware function which exist in vmware module vmware.vmware() ## To call sub function which exist in linux module linux.sub() # To import linux module from one package from one import linux # To import windows module from two package from one.two import windows # To import only os function from mac module from one.three.mac import os ## To call sub function from linux module linux.sub() ## To print name variable form windows module print(windows.name) ## To call os function which imported from mac module os()

27 JSON module in python

 JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation. import json Example Convert from JSON to Python: import json # some JSON: x =  '{ "name":"John", "age":30, "city":"New York"}' # parse x: y = json.loads(x) # the result is a Python dictionary: print(y["age"]) Example Convert from Python to JSON: import json # a Python object (dict): x = {   "name": "John",   "age": 30,   "city": "New York" } # convert into JSON: y = json.dumps(x) # the result is a JSON string: print(y)

26 math module in python

 ---math module----- Use math module, to perform mathematical tasks on numbers Built-in Math Functions The min() and max() functions can be used to  find the lowest or highest value in an iterable: x = min(2, 6, 8) y = max(50, 100, 205) print(x) print(y) ---------- The abs()  The pow(x, y) function  --------------------------------------- The Math Module ---------------------- Python has also a built-in module called math,  which extends the list of mathematical functions. To use it, you must import the math module: import math Example import math x = math.sqrt(9) print(x) Example import math x = math.ceil(1.4) y = math.floor(1.4) print(x) # returns 2 print(y) # returns 1 The math.pi constant, returns the value of PI (3.14...): Example import math x = math.pi print(x)

25 datetime module in python

  ----- datetime to work with dates as date objects. ----Example---- Import the datetime module and display the current date: import datetime x = datetime.datetime.now() print(x) ----When we execute the code from the example above the result will be: 2021-10-02 21:34:06.726296 The date contains year, month, day, hour, minute, second, and microsecond. -----Example Return the year and name of weekday: import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A")) -------Creating Date Objects------- To create a date, we can use  the datetime() class (constructor) of the datetime module. -----Example------ Create a date object: import datetime x = datetime.datetime(2020, 5, 17) print(x) strftime(), and takes one parameter, format,  to specify the format of the returned string: Example Display the name of the month: import datetime x = datetime.datetime(2018, 6, 1) print(x.strftime("%B"))

24 Threading in python

  ''' 1. Threading is used to run multiple jobs concurrently(at the same time) 2. Using threading module we can achive threading in python.    target: the function to be executed by thread    args  : the arguments to be passed to the target function    name  : We can specify a name to the thread    join  : Using join function we keep a thread to wait till ending the thread ''' import threading import time def first_fun():     print(' \n first_thread started')     time.sleep(5)     print(' \n first_thread ended') def second_fun(a,b):     print(' \n second_thread started')     time.sleep(5)     print(' \n second_thread ended') # print(time.ctime()) # first_fun() # second_fun(3,4) # print(time.ctime()) ft = threading.Thread(target=first_fun) st = threading.Thread(target=second_fun, args=('sriram','chowdary')) print(time.ctime()) ft.start() st.start() st.join() print(time.ctime()) ### Thread count ''' 1. th

23 Praramiko module

 ''' 1. Praramiko module is used to do operations on remote machine. 2. used to run commands on remote host and copy file from local to remote and remote to local. 1. To install module ==> python -m pip install paramiko ''' import paramiko h_name = '10.8.2.5' u_name ='siellamp' p_word = '8Aug2019' port_no = 22 # To create ssh object ssh = paramiko.SSHClient() # To avoid popups  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # To create a connection on remote machine ssh.connect(h_name, username=u_name, password=p_word, port=port_no) # To run commnd on remote host  stdin, stdout, stderr = ssh.exec_command('mkok /home/smellamp/sriram/RAMESH') # To get command output print(' \n stdout is ::', stdout.readlines()) # To get error message if any failures  print(' \n stderr is ::', stderr.read()) ssh.close() import paramiko host_name = '10.1.2.35' u_name ='admin' p_word = '8Aug2019' po

22 logging module

 ''' 1. Using logging module we can log based on severity level. 2. By default, there are 5 standard levels indicating the severity of events.  3. Log levels are ==>  INFO, DEBUG, WARNING, ERROR, CRITICAL 4. The default level is WARNING ''' import logging logging.info(" TEST 1 ") logging.debug(" TEST 2 ") logging.warning(" TEST 3 ") logging.error("   TEST 4 ") logging.critical(" TEST 5 ") '''  datefmt='%m/%d/%Y %I:%M:%S %p' ''' import logging logging.basicConfig(level=logging.DEBUG,                     format='%(levelname)s %(asctime)s %(message)s ',                     datefmt='%m/%d/%Y %H/%M/%S %p',                     filename='debug.log',                     filemode='w'                     ) logging.info(' :: TEST 1 ') logging.debug(' :: TEST 2 ') logging.warning(' :: TEST 3 ') logging.error(' :: TEST 4 ') logg

21 re (Regular Expression) - module

  1. Using regular expressions we can find a string based on pattern. 2. Using re module we can do regular expression operations # Regular Expression Patterns '\d  ==>  Match a digit   : [0-9] '\D  ==>  Match a nondigit: [^0-9] '\s  ==>  Match a whitespace character '\S  ==>  Match a nonwhitespace character '\w  ==>  Match a single character : [A-Za-z0-9_] '\W  ==>  Match a single nonword character: [^A-Za-z0-9_] '\n  ==>  Match a new line character +   ==>  Matches 1 or more occurrence of preceding expression. *   ==>  Matches 0 or more occurrence of preceding expression. ?   ==>  Matches 0 or 1 occurrence of preceding expression. ^   ==>  Matches beginning of line. $  ==>  Matches end of line. |   ==>  To do OR operation .   ==>  Matches any single character except newline. '\'   ==>  Used to escape any special character and interpret it literal ()  ==>  Using parentheses we can create a groups []  ==

20 Time module in python

  import time print(' \n Before sleep ', time.ctime()) time.sleep(10) print(' \n After sleep  ', time.ctime())

19 sys module in python

  ''' 1. Using sys module we can do system related operation. ''' import sys print(sys.version) ## to append path #sys.path.append(r'C:\\Users\\sriram\\Desktop\\akr') ## To exit from execution print(' \n Before exit') sys.exit() print(' \n After exit') -------------Input and Output using sys The sys modules provide variables for better control over input or output.  We can even redirect the input and output to other devices.  This can be done using three variables –  1.stdin 2.stdout 3.stderr ----stdin---: It can be used to get input from the command line directly.  It used is for standard input.  It internally calls the input() method.  It, also, automatically adds ‘\n’ after each sentence. import sys for line in sys.stdin:     if 'q' == line.rstrip():         break     print(f'Input : {line}') print("Exit") --------stdout-------: A built-in file object that is  to  the interpreter’s standard output stream

18 os -- predefined module

 ''' 1. The OS module in python provides functions for  interacting with the operating system.  ''' import os print(dir(os)) # To create a directory #os.mkdir('TODAY') # To remove directory #os.rmdir("TODAY") # To create a file #open("my_file.py", 'w')   # To rename a file use os module #os.rename('my_file.py', 'RRR.py') # To check file is exist or not return True is exist or False #status = os.path.isfile('RRR.py') #print(' Status :', status) # To run system commands #print(os.system('dir')) #os.system('python today.py')

17 Modules in python

 1. Any .py file is a module in python 2. Using module we can re use the code # How to import a module ? We can import in two ways     1. import     2. from import # Difference between import and from import 1. Using import we can import entire module and  we have to use module name as prefix for each module attribute. 2. Using from import we can import required attribute from module and  no need to give prefix as module name to use module attribute. 1) import statement ''' 1. we can import a module using import keyword ''' import base_module # Print a variable from base_module #print(base_module.names) ## call a add function from base_module #base_module.add() ## call a sum function from base_module #r = base_module.sum(20,50) #print(' Sum value is :', r) 2) from import statement ''' 1. Import module attributes using "from" keyword ''' ## to import only names variable #from base_module import names ## to import only nam

16 file handling in python

 1. Using file handling we can do file operations # How to open a file in python ? 1. We can open a file two ways in python      1. open()     2. With open() # OPEN 1. Using open we can open only one file at a time and we have to close a file explicity # WITH OPEN  1. Using with open we can open multiple files at a time and no need to close files explicity # File Open Modes In Python r    ==>     It opens a file for read only. w    ==>     It allows write-level access to a file. If the file already exists, then it’ll get overwritten. It’ll create a new file if the same doesn’t exist. a    ==>     It opens the file in append mode. a+   ==>     It opens a file FOR append AND read rb   ==>     It opens a binary file for read 1)  Read file fh = open('names.txt', 'r') ## To open a file from another path #fw = open(r'C:\Users\smellamput001\Desktop\BACKUP_EPRO\RRR.txt', 'r') ## Using read we can read entire file data and return in string format f

15 Function in python

1. Using functions we can give a name to the block of code. 2. Using functions we can re use the code. 3. Using def keyword we can create a function. # Use of Parameters  1. Using parameters we can make a function dynamic 2. Using parameters we can pass values to the function 3. python function support 4 types of parameters     1. Required or positional arguments   add(a,b)-------add(3,4)     2. Keyword arguments---------add(a,b)--------add(b=3,a=7)     3. Default arguments---------add(a,b=3)------add(6)     4. Variable length arguments(Args, Kwargs)---args  *a,   kwargs   **a ### Simple function #function creation def add():     print( 3 + 6 ) # function call add() 1)  required arguments. ''' 1. We should give values to the required arguments. 2. The given values pass in correct positional order. ''' def add(a,b):     print(' A value is :', a)     print(' B value is :', b) add(4, 6) #add(5, 8) #add(42, 98) 2) Key word arguments ''' 1

10 Interview question on python

  # What is python ?     1. Python is a high level interpriter programing language.     2. Python supports OOP.     3. Python language used in many areas for developing web applications,  automate webapplications with selenium ,Machine Learning, Automation, IOT,  Network Programming, Text processing and Multimedia. # Advantages of python ?     1. Python is easy to learn and use     2. Python syntax is easy to use and Simple.     3. Python supports OOP, modules and packages.     4. It is a Interpreted language     5. Compatible with Major Platforms     6. Python has Extensive Support Libraries like(panda, numpy, matplotlib) and  frameworks(django, flask, bottle and Robot Framework)     7. Python is a open source. # Dis Advanatges in python ?     1. Python runs only on single core.     2. It is not suitable for mobile applications.     3. Speed: Python is slower than C or C++. But of course,  Python is a high-level language, unlike C or C++ it's not closer to hardware. # Which python

9 Data types questions

 1. What are the data types available in python ? they are 6 type       1) number,      2) string,      3) list,      4) tuple,      5) dictionary,      6) set, 2. Difference between list and tuple ? 3. Difference between set and tuple ? 4. Difference between Dictionary and set ? 5. Difference between Number and string ? 6. What is Dictionary ?    1. Dictionary is a collection of key value pairs.    2. Using dictionary we can represent data meningfully.    3. Based on key we can do operation on each value.    4. Using curly brackets "{}" we can create a dictionary    5. dictionary is a mutable object 7. Use of type() function ? 8. Use of dir() function ? 9. Use of id() function ? 10. Use of slicing operaions ? 11. Use of slicing opertions ? 12. How to get first 4 cherecters from string using slicing operation ? ## Number  1. What is number 2. How to convert number data type into string ? ## String 1. What are the string operations ? 2. How to concordinate two strings ? 3. How

8 slicing_operations

  ''' 1. Using slicing operation we can get range of values from list and  sub string from string. ''' l = [7,89,34,2,5,12,7] print(' \n ', l[1:5]) # print(' \n ', l[2:6]) # print(' \n ', l[1:70]) # print(' \n ', l[3:]) # print(' \n ', l[0:5]) # print(' \n ', l[:6]) # print(' \n ', l[:-4]) # print(' \n ', l[-2:-4]) # print(' \n ', l[-4:-2]) # print(' \n ', l[0:6:2]) #print(' \n ', l[::3]) # print(' \n ', l[::-1]) #print(' \n ', l[::-3]) ## Slicing operation on string s = 'sriram' print(' \n ', s[::-1]) #print(' \n ', s[0:3])

7 Multi_dimensional_list in python

 ''' 1. multi-dimensional list contains another list. ''' l = [1,2,['A',['siva','ram',{'name':'BABU', 'eid':77}],'B','C'],'uma',{'n':'one',88:99},(8,9)] # To print 99 value from list inside dictionary print(l[4][88]) # to print ram print(l[2][1][1]) print(l[2][2]) # To get all keys from dictionary #print(l[2][1][2].keys())    

6 Set data type

 ''' 1. Set is used to store unique values & it doesn't contains duplicate values. 2. Using set we can do set operations 3. Using curly brackets "{}" we can create a set 4. Set doesn't support indexing  5. Set is a mutable object ''' # To create a set eids = {45,33,45,23,33} # To print a set print(' Emp ids are ==> ',eids ) print(id(eids)) # To  Delete a set #del eids

5 Dictionary data types

 ''' 1. Dictionary is a collection of key value pairs. 2. Using dictionary we can represent data meningfully. 3. Based on key we can do operation on each value. 4. Using curly brackets "{}" we can create a dictionary 5. dictionary is a mutable object ''' # To create a dictionary emp_det = {'ename':'umamahesh', 'eid':36, 'dname':'IT', 'did':45, 'age':33} # emp = {'ename':'umamahesh', True:36, None:'IT', 99:45, 88.90:33} # To update  emp_det['dname'] = 'SALES' # To Delete particular key value pair del emp_det['eid'] # To delete total dictionary del emp_det # To print particular key value pair  print(emp_det['age']) #  ******* to update dictionary or add at end >>>emp_det.update({'sal':30000}) >>>print(emp_det) {'ename': 'umamahesh', 'eid': 36, 'dname': 'SALES', 'did': 45,

4 Tuple data types

 ''' 1. Tuple is used to store multiple values and  we can do operation on each value based on index. 2. Tuple is a read only object,  we can't do update,insert and delete operations. 3. Using parentheses "()" we can create a tuple 4. tuple is a immutable object 5. To store sensitive data we use tuple. ''' # To create a tuple names = ('umamahesh','kumar','balu','ram', 567, 99.9) # Tuple doesn't support for item deltion and update names[3] = 'ok' del names[3] # To print particular value based on index print(names[4]) print(names[-1]) # To delete a total tuple del names

2 String data types

Image
 ''' 1. Using string we can store any value but  it should be in single quotes or double quotes. 2. String is a immutable object ''' # To define a string variable # name = 'sri123$#%   &' # print('name is:', name) # print('\n memory location for name is :', id(name)) # If string contains double quote  name1 = " I don't 'know' umamahesh" print('name is:', name1) print('\n memory location for name is :', id(name1)) # If string contains double quote  # name2 = ' I know "sriram"' # If string contains single quote and double quote  #name3 = ''' I don't know "sriram"''' # To update #name = 'kumar' #print(name) # To Delete  #del name  # To Print on console #print(' Name is : ', name)

3 List Data Types

 ''' 1. List is used to store multiple values and  we can do operation on each value based on index. 2. Using square brackets "[]" we can create a list 3. List is a mutable object ''' # To create a list l=[1,2,3,4,5] names = ['uma','kumar','balu','mahesh', 567, 99.9] print(names) print(names[0]) print(id(names)) # To update a particular value # names[0] = 'uma mahesh' # print(names[0]) # print(id(names)) # To delete particular value in list #del names[2] # To delete a total list #del names # To print particular value based on index #print(names[4]) #print(names[-2])