SlideShare a Scribd company logo
Lists
 Creating Lists,
 Accessing the Elements of a List,
 Negative List Indices,
 List Slicing [Start: end], List Slicing with Step Size,
 Python Inbuilt Functions for Lists,
 The List Operator, List Comprehensions,
 List Methods, List and Strings, Splitting a String in List,
 Passing List to a Function, Returning List from a Function.
Prepared by Dr. C. Sreedhar
# Lists are used to store multiple items in a single variable.
# List items can be of similiar items, different items,duplicates
list1 = ["cse", "cst", "csbs"]
list2 = [10, 50, 60, 80, 40]
list3 = [True, False, False]
list4 = ["cse4a","cse4b","cse4a","ece"]
print(list1)
print(list2)
print(list3)
print(list4[1])
['cse', 'cst', 'csbs']
[10, 50, 60, 80, 40]
[True, False, False]
cse4b
Prepared by Dr. C. Sreedhar
# Accept list items from user uslng list() constructor
l1=input(list())
print(l1)
# Access the elements using index [ ] operator
list4 = ["cse4a","cse4b","cse4a","ece"]
print(list4[2])
cse4b
# Slicing the list using
#Name_of_Variable_of_a_List[Start_Index: End_Index]
list4 = ["cse4a","cse4b","cse4a","ece"]
['cse4b',
'cse4a']
Prepared by Dr. C. Sreedhar
Prepared by Dr. C. Sreedhar
Lists in python
 Lists are used to store multiple items in a single variable.
 List items can be of any data type. Example:
 list1 = ["cse", "cst", "csbs"]
 list2 = [10, 50, 60, 80, 40]
 list3 = [True, False, False]
 List allows duplicates. Example:
 cse4a = ["ram", "shyam", "ram", "sree", "dennis"]
 print(cse4a)
 List allows different data types. Example
Prepared by Dr. C. Sreedhar
Creating a list with w/o using constructor of the list class
 Lists can be created in Python with constructor and w/o constructor
Using list Constructor
 Create an empty list. L1 = list();
 Create a list with any three integer elements, such as 10, 20 and 30.
L2 = list([10,20,30])
 Create a list with three string elements, such as “Apple”, “Banana” and
“Grapes”. L3 = list([“Apple”,”Banana”,”Grapes”])
 Create a list using inbuilt range() function. L4 = list(range(0,6))
 Create a list with inbuilt characters X, Y and Z. L5=list(“xyz”)
 Create a list with any three integer elements, such as 10, 20 and 30.
L1=[10,20,30]
Prepared by Dr. C. Sreedhar
ACCESSING THE ELEMENTS OF A LIST
 index [] operator is used to access them. The syntax is:
Name_of_Variable_of_a_List[index]
 L1=([10,20,30,40,50])
>>> List1=[10,20,30,40,50,60]
>>> List1[-3]
Output
40
Prepared by Dr. C. Sreedhar
LIST SLICING [START: END]
 Name_of_Variable_of_a_List[Start_Index: End_Index]
>>> L1=([10,20,30,40,50])
>>> L1[1:4]
Output
20,30,40
>>> L1[2:5]
Output
Prepared by Dr. C. Sreedhar
LIST SLICING WITH STEP SIZE
 List_Name[Start_Index:End_Index:Step_Size]
>>>MyList1=[“CSE”,1,”CST”,2,”ECE”,3,”EEE”]
>>>New_List1=MyList1[0:6:2]
print(New_List1)
Output
[‘CSE’, ‘CST’, ‘ECE’] >>> List1=[“Python”,450,”C”,300,”,C++”,670]
>>> List1[0:6:3]
Output
Prepared by Dr. C. Sreedhar
PYTHON INBUILT FUNCTIONS FOR LIST
Prepared by Dr. C. Sreedhar
 + Operator: The concatenation operator is used to join two lists.
 a=[1,2,3] b=[4,5,6] a+b # [1, 2, 3, 4, 5, 6]
 * Operator: The multiplication operator is used to replicate the
elements of a list.
 List1=[10,20] List2=[20,30] List3=2*List1 #[10, 20, 10, 20]
 in Operator: The in operator used to determine whether an element
is in a list. It returns True if the element is present and False if the
element is absent in the list.
 List1= [10,20]
 >>> 40 in List1
 False
LIST OPERATOR Prepared by Dr. C. Sreedhar
LIST OPERATOR
 isOperator
 >>> A=’Microsoft’
 >>> B=’Microsoft’
 >>> A is B
 True
 >>> A=[‘A’,’B’,’C’]
 >>> B=[‘A’,’B’,’C’]
 >>> A is B #Check if two lists refer to the same Object
 False
Prepared by Dr. C. Sreedhar
del Operator
Lst=[10,20,30,40,50,60,70]
>>> del Lst[2] #Removes 3rd element from the List
>>> Lst
[10, 20, 40, 50, 60, 70]
Lst=[10,20,30,40,50,60,70]
>>> del Lst[-1]
>>> Lst #Removes last element from the List
[10, 20, 30, 40, 50, 60]
>>> Lst=[10,20,30,40,50,60,70]
>>> del Lst[2:5] #Removes element from index position 2 to 4
>>> Lst
[10, 20, 60, 70]
>>> Lst=[10,20,30,40,50,60,70]
>>> del Lst[:] #Removes all the element from the List
>>> Lst
[]s
Prepared by Dr. C. Sreedhar
LIST COMPREHENSIONS
 List comprehension is used to create a new list from existing sequences
Normal Code
List1= [10, 20, 30, 40, 50]
for i in range(0,len(List1)):
List1[i]=List1[i]+5 # [15, 25, 35, 45, 55]
Using List Comprehension
List1= [10,20,30,40,50]
List1= [x+10 for x in List1] # [20, 30, 40, 50, 60]
Prepared by Dr. C. Sreedhar
Unit 4
• Modules: Reusing Code with Modules and Packages,
Understanding Python Modules, Everyday Module Usage,
Advanced Module Behavior, Combining Modules into
Packages
• Exceptions: When Something Goes Wrong, Classes of
Exceptions, A Final Note on Pythonic Exception Handling.
• File Handling: Need of File Handling, Text Input and
Output, The seek() Function, Binary Files, Accessing and
Manipulating Files and Directories on a Disk.
Prepared by Dr. C. Sreedhar
• os
– os.getcwd()
– os.fspath(path)
– os.getlogin()
• ipaddress:
–ipaddress.IPv4Address(address)
–ipaddress.IPv6Address(address)
• math:
– math.factorial(x)
– math.gcd(n1,n2)
– math.lcm(n1,n2)
– math.trunc(x)
– math.pow(x, y)
– math.pi
• random:
– random.randint(a,b)
– random.uniform(a,b)
• time:
– time.clock_gettime()
– time.clock_gettime_ns()
Module: Builtin Modules
Prepared by Dr. C. Sreedhar
Modules: Create and import
• 1. Open Python IDLE (Start --> Python IDLE)
• 2. File --> New File
• 3. ---- type the following code----
def greeting(name):
print("Hello, " + name)
• 4. Save with module1.py (in Desktop or any folder)
• 5. Pyhton IDLE ==> File --> New File
• 6. ------ type the following code ----
import module1
module1.greeting("CSE4A")
• 7. Save as runmodule.py (in Desktop or any folder)
• 8. In Python IDLE, click on Run --> Run Module
from <module_name> import *
from <module_name> import <name> as <alt_name>
Prepared by Dr. C. Sreedhar
module2.py
----------------------------------------------
def sum_list(lst):
print('Sum=',sum(lst))
---------------------------------------------
summodule.py
---------------------------------------------
import module2
l1=[10,20,30,40]
module2.sum_list(l1)
Modules: Create and import
Prepared by Dr. C. Sreedhar
In python, the inbuilt __import__() function helps
to import modules in runtime
Syntax:
__import__(name, globals, locals, fromlist, level)
Ex:
math_score = __import__('math', globals(), locals(), [], 0)
print(math_score.fabs(17.4))
Prepared by Dr. C. Sreedhar
Package
• A package is basically a directory with Python file
and file with the extension as _init_.py.
• Steps to create package:
– create a package (folder). The name of package, say, My _ First _ Package
– Create _ init _ .py file inside the created package My_First_Package.
– The directory should contain a file named _init_.py. This file can be empty or it
may contain valid Python code.
– create two different .py files, i.e. a.py and b.py with code
a.py
def call_A():
print(“This is first program”)
b.py
def call_B():
print(“This is second”)
>>> My_First_Package.a.call_A()
This is first program
>>> My_First_Package.b.call_B()
This is second
_init_.py
import My_First_Package.a
import My_First_Package.b
Prepared by Dr. C. Sreedhar
# GPREC/CSBS/__init__.py (Empty file)
# GPREC/CSBS/csbs4sem.py
print("In CSBS branch")
# GPREC/CSE/__init__.py
from . import cse4a
from . import cse4b
# GPREC/CSE/cse4a.py
print("In CSE 4A Class")
# GPREC/CSE/cse4b.py
print("In CSE 4B Class")
# GPREC/CSE/cse4c.py
print("In CSE 4C Class")
# world/__init__.py
from . import CSBS
from GPREC import CSE
import GPREC.CSE.cse4a
from GPREC.CSE import cse4b
Prepared by Dr. C. Sreedhar
Exceptions
• An exception is an event, which occurs during the execution of a program,
that disrupts the normal flow of the program's instructions.
• Exception: Base class for all exceptions
• ArithmeticError: Base class for all errors that occur for numeric calculation.
• OverflowError: Raised when a calculation exceeds maximum limit for a numeric type.
• FloatingPointError: Raised when a floating point calculation fails.
• ZeroDivisionError: Raised when division or modulo by zero takes place for numeric
• AttributeError: Raised in case of failure of attribute reference or assignment.
• EOFError: Raised when end of file is reached.
• ImportError: Raised when an import statement fails.
• IndexError: Raised when an index is not found in a sequence.
• EnvironmentError: Base class for all exceptions that occur outside Python environment.
• SyntaxError: Raised when there is an error in Python syntax.
• TypeError: Raised when an operation is attempted that is invalid for specified data type.
Prepared by Dr. C. Sreedhar
try:
<body>
except <ExceptionType1>:
<handler1>
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>
Prepared by Dr. C. Sreedhar
try:
num1,num2 = eval(input("Enter two numbers,separated by a comma:"))
result = num1 / num2
print("Result is", result)
except ZeroDivisionError:
print("Division by zero is error !!")
except SyntaxError:
print("Comma is missing. Enter nos separated by comma like this 1, 2")
except:
print("Wrong input")
else:
print("No exceptions")
finally:
print("This will execute no matter what“)
Prepared by Dr. C. Sreedhar
try:
a = [1, 2, 3]
print (a[3])
except LookupError:
print ("Index out of bound error.")
else:
print ("Success")
Prepared by Dr. C. Sreedhar
try:
age= int(input())
assert (age>0 and age<100)
# True: moves to the next line ie., print age; False: returns Assertion Error
except AssertionError:
print("Not valid age.")
except:
print("Invalid data entered")
else:
print("Age is:",age)
Prepared by Dr. C. Sreedhar
try:
age= int(input("Enter your age:"))
if age<0:
raise ValueError
except ValueError:
print("Age cannot be less than zero.")
else:
print("Age is:",age)
Prepared by Dr. C. Sreedhar
Format:
<file variable> = open(<file name>, "r")
Example:
filename = input("Enter name of input file: ")
inputFile = open(filename, "r")
Python File handling
Prepared by Dr. C. Sreedhar
Modes Description
r Opens a file for reading only, default mode.
rb Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing
rb+ Opens a file for both reading and writing in binary format
w Opens a file for writing only. Overwrites the file if the file exists.
Wb Opens a file for writing only in binary format. Overwrites the file if the file exists
w+ Opens a file for both writing and reading, Overwrites file if file exists
Prepared by Dr. C. Sreedhar
Example:
file2 = open(“cse4a.txt", "wb")
print ("Name of the file: ", file2.name)
print ("Closed or not : ", file2.closed)
print ("Opening mode : ", file2.mode)
This would produce following result:
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Prepared by Dr. C. Sreedhar
Reading contents from file
inputFileName = input("Enter name of input file:")
inputFile = open(inputFileName, "r")
print("Opening file", inputFileName, " for reading.")
for line in inputFile:
sys.stdout.write(line)
inputFile.close()
print("Completed reading of file", inputFileName)
Prepared by Dr. C. Sreedhar
Alternate way to read contents from file
inputFileName = input ("Enter name of input file: ")
inputFile = open(inputFileName, "r")
print("Opening file", inputFileName, " for reading.")
line = inputFile.readline()
while (line != ""):
sys.stdout.write(line)
line = inputFile.readline()
inputFile.close()
print("Completed reading of file", inputFileName)
Prepared by Dr. C. Sreedhar
Writing contents
fo = open(“cse4a.txt", "wb")
fo.write("Welcome to CSE4A n");
fo.close()
Prepared by Dr. C. Sreedhar
Writing contents from one file into another
inputFileName = input("Enter file name to read grades from: ")
outputFileName = input("output filename to write GPA's to: ")
inputFile = open(inputFileName, "r")
outputFile = open(outputFileName, "w")
print("Opening file", inputFileName, " for reading.")
print("Opening file", outputFileName, " for writing.")
gpa = 0
Prepared by Dr. C. Sreedhar
seek()
• seek() function is used to change the position
of the File Handle to a given specific position.
Prepared by Dr. C. Sreedhar
Unit 5
Object-Oriented Programming:
• Class, Objects and Inheritance: Defining Classes, The
Selfparameter and Adding Methods to a Class,
• Display Class Attributes and Methods, Special Class Attributes,
Accessibility, The __init__ Method (Constructor),
• Passing an Object as Parameter to a Method, __del__()
(Destructor Method), Class Membership Tests,
• Method Overloading, Operator Overloading, Inheritance, The
Object Class.
Prepared by Dr. C. Sreedhar
Class and attributes
class Example :
x = 10
print(Example.x)
class Example:
x = 10
y = 20
print(Example.x)
print(Example.y)
Prepared by Dr. C. Sreedhar
Class and method
class Example:
x=10
y=20
def show(obj):
print("x=",obj.x)
print("y=",obj.y)
Example.show=classmethod(Example.show)
Example.show()
Prepared by Dr. C. Sreedhar
Constructor
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("Total students:",Student.count)
Prepared by Dr. C. Sreedhar
Class and Object
class Student:
def __init__(self, name, percentage):
self.name = name
self.percentage = percentage
def show(self):
print("Name:", self.name,“percentage:", self.percentage)
stud = Student("Sreedhar", 90)
stud.show()
Prepared by Dr. C. Sreedhar
Data encapsulation
class Employee:
def __init__(self, name, empid):
self.name = name
self.empid = empid
def show(self):
print("Name: ", self.name, "and ID:", self.empid)
E = Employee("Sreedhar", 6666)
print(E.name)
print(E.empid)
Prepared by Dr. C. Sreedhar
Class attributes
class MyClass(object):
var = 10
def set_val(self):
self.b = 100
ob1 = MyClass()
print(ob1.var) # This will fetch the class attribute 10.
ob1.set_val()
print(ob1.b) # This will fetch the class attribute 100
Prepared by Dr. C. Sreedhar
Class constructor: Example
class gprecclass:
def __init__ (self, section):
# self allows to attach parameter to the class
self.section =section
p = gprecclass("CSE4A")
print(p.section)
Prepared by Dr. C. Sreedhar
__init__ method: Constructor
class MyNum(object):
def __init__(self):
print("Calling __init__() constructor!n")
self.val = 0
def increment(self):
self.val = self.val + 1
print(self.val)
dd = MyNum()
dd.increment() # will print 1
dd.increment() # will print 2
Prepared by Dr. C. Sreedhar
Constructor
class Rectangle(object):
def __init__(self, l, w):
self.length = l
self.width = w
def area(self):
return self.length*self.width
a = Rectangle(2,10)
print(a.area())
Prepared by Dr. C. Sreedhar
Methods
class Circle:
pi = 3.14
def __init__(self, radius=1):
self.radius = radius
self.area = radius * radius * Circle.pi
def setRadius(self, new_radius):
self.radius = new_radius
self.area = new_radius * new_radius * self.pi
def getCircumference(self):
return self.radius * self.pi * 2
c = Circle()
print('Radius is: ',c.radius)
print('Area is: ',c.area)
print('Circumference is:
',c.getCircumference())
Prepared by Dr. C. Sreedhar
Class and methods
class Subject:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("Subject ID:%d Name:%s”%(self.id, self.name))
ppy = Subject("Python Programming", 101)
ds = Subject("Data Structures", 102)
ppy.display()
ds.display()
Prepared by Dr. C. Sreedhar
Public access modifier
class Bank:
def __init__(self, name, pin):
# public data members
self.bankname = name
self.bankpin = pin
# public member function
def displaypin(self):
# accessing public data member
print("Pincode: ", self.bankpin)
obj = Bank("Union Bank", 518007)
print("Bank Name: ", obj.bankname)
obj.displaypin()
Prepared by Dr. C. Sreedhar
Private specifier
class Bank:
bankname="SBI"
__custname = None # privatemember
__custage = 20
__custbranch = None
def __init__(self, name, age, branch):
self.__custname = name
self.__custage = age
self.__custbranch = branch
# private member function
def __displayDetails(self):
print("Customer Name: ", self.__custname)
print("Customer Age: ", self.__custage)
print("Cust Branch: ", self.__custbranch)
# public member function
def accessPrivateFunction(self):
# accessing private member function
self.__displayDetails()
obj = Bank("Sree", 25, "SN Colony")
print(obj.bankname)
obj.accessPrivateFunction()
Prepared by Dr. C. Sreedhar
Inheritance
class Base:
def func1(self):
print('This is Base class')
class Derived(Base):
def func2(self):
print('This is Derived class')
obj = Derived()
obj.func1()
obj.func2()
Prepared by Dr. C. Sreedhar
Inheritance
class Date(object):
def get_date(self):
print("2022-05-3")
class Time(Date):
def get_time(self):
print("14:10:00")
dt = Date()
dt.get_date()
print("----------“)
tm = Time()
tm.get_time()
tm.get_date()
Prepared by Dr. C. Sreedhar
Multiple Inheritance
class A(object):
def method1(self):
print("doing this in A")
class B(A):
pass
class C(object):
def method1(self):
print("doing this in C")
class D(B, C):
pass
d_instance = D()
d_instance.method1()
print("nPrint the Method Resolution Order")
print(D.mro())
Prepared by Dr. C. Sreedhar
Method Overloading
class Person:
def M1(self, name=None):
if name is not None:
print('Name: ' + name)
else:
print('Default name ')
obj = Person()
obj.M1()
obj.M1('ABCDEF‘)
Prepared by Dr. C. Sreedhar
Method Overloading
class A:
def __init__(self, a):
self.a = a
# adding two objects
def __add__(self, o):
return self.a + o.a
ob1 = A(10)
ob2 = A(30)
ob3 = A("CSE4A")
ob4 = A(" ECE4A")
print(ob1 + ob2)
print(ob3 + ob4)
Prepared by Dr. C. Sreedhar
Operator Overloading
import math
class Circle:
def __init__(self, radius):
self.__radius = radius
def setRadius(self, radius):
self.__radius = radius
def getRadius(self):
return self.__radius
def area(self):
return math.pi * self.__radius ** 2
def __add__(self, circle_object):
return Circle(self.__radius + circle_object.__radius)
def __lt__(self, circle_object):
return (self.__radius < circle_object.__radius)
def __gt__(self, circle_object):
return (self.__radius > circle_object.__radius)
def __str__(self):
return "Circle area = " + str(self.area())
c1 = Circle(20)
c2 = Circle(30)
c3 = c1 + c2
print(c1.getRadius())
print(c2.getRadius())
print(c3.getRadius())
print(c1 < c2)
print(c3 > c2)
print(str(c1))
print(str(c2))
print(str(c3))
Prepared by Dr. C. Sreedhar

More Related Content

What's hot (20)

Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
MohammadSalman129
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
Sathish Narayanan
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
DataFrame in Python Pandas
DataFrame in Python PandasDataFrame in Python Pandas
DataFrame in Python Pandas
Sangita Panchal
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
mikeymanjiro2090
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
Sreedhar Chowdam
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
Sreedhar Chowdam
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Arrays In C
Arrays In CArrays In C
Arrays In C
yndaravind
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
Hitesh Kumar
 
Enumerated data types in C
Enumerated data types in CEnumerated data types in C
Enumerated data types in C
Arpana shree
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
baabtra.com - No. 1 supplier of quality freshers
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
KristinaBorooah
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C Language
Adnan Khan
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
Mohd Sajjad
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
Wingston
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
MohammadSalman129
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
DataFrame in Python Pandas
DataFrame in Python PandasDataFrame in Python Pandas
DataFrame in Python Pandas
Sangita Panchal
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
mikeymanjiro2090
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
Sreedhar Chowdam
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
Sreedhar Chowdam
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
Hitesh Kumar
 
Enumerated data types in C
Enumerated data types in CEnumerated data types in C
Enumerated data types in C
Arpana shree
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
Rassjb
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
KristinaBorooah
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C Language
Adnan Khan
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
Mohd Sajjad
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
Wingston
 

Similar to Python Programming: Lists, Modules, Exceptions (20)

GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
Guru Nanak Technical Institutions
 
Unit 4.pptx python list tuples dictionary
Unit 4.pptx python list tuples dictionaryUnit 4.pptx python list tuples dictionary
Unit 4.pptx python list tuples dictionary
shakthi10
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
R.K.College of engg & Tech
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
AnitaDevi158873
 
013 LISTS.pdf
013 LISTS.pdf013 LISTS.pdf
013 LISTS.pdf
aryanverma695462
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
AshaWankar1
 
Python _dataStructures_ List, Tuples, its functions
Python _dataStructures_ List, Tuples, its functionsPython _dataStructures_ List, Tuples, its functions
Python _dataStructures_ List, Tuples, its functions
VidhyaB10
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
Panimalar Engineering College
 
"Automata Basics and Python Applications"
"Automata Basics and Python Applications""Automata Basics and Python Applications"
"Automata Basics and Python Applications"
ayeshasiraj34
 
Pytho lists
Pytho listsPytho lists
Pytho lists
BMS Institute of Technology and Management
 
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuufPYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
DeepakRattan3
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
Siva Arunachalam
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
Yagna15
 
Introduction To Programming with Python-4
Introduction To Programming with Python-4Introduction To Programming with Python-4
Introduction To Programming with Python-4
Syed Farjad Zia Zaidi
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
Koteswari Kasireddy
 
Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Python Usage (5-minute-summary)
Python Usage (5-minute-summary)
Ohgyun Ahn
 
python language programming presentation
python language  programming presentationpython language  programming presentation
python language programming presentation
lbisht2
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
Abdul Haseeb
 
Lists and its functions in python for beginners
Lists and its functions in python for beginnersLists and its functions in python for beginners
Lists and its functions in python for beginners
Mohammad Usman
 
Unit 4.pptx python list tuples dictionary
Unit 4.pptx python list tuples dictionaryUnit 4.pptx python list tuples dictionary
Unit 4.pptx python list tuples dictionary
shakthi10
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
AshaWankar1
 
Python _dataStructures_ List, Tuples, its functions
Python _dataStructures_ List, Tuples, its functionsPython _dataStructures_ List, Tuples, its functions
Python _dataStructures_ List, Tuples, its functions
VidhyaB10
 
"Automata Basics and Python Applications"
"Automata Basics and Python Applications""Automata Basics and Python Applications"
"Automata Basics and Python Applications"
ayeshasiraj34
 
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuufPYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
DeepakRattan3
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
Siva Arunachalam
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
Yagna15
 
Introduction To Programming with Python-4
Introduction To Programming with Python-4Introduction To Programming with Python-4
Introduction To Programming with Python-4
Syed Farjad Zia Zaidi
 
Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Python Usage (5-minute-summary)
Python Usage (5-minute-summary)
Ohgyun Ahn
 
python language programming presentation
python language  programming presentationpython language  programming presentation
python language programming presentation
lbisht2
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
Abdul Haseeb
 
Lists and its functions in python for beginners
Lists and its functions in python for beginnersLists and its functions in python for beginners
Lists and its functions in python for beginners
Mohammad Usman
 
Ad

More from Sreedhar Chowdam (20)

DBMS Nested & Sub Queries Set operations
DBMS Nested & Sub Queries Set operationsDBMS Nested & Sub Queries Set operations
DBMS Nested & Sub Queries Set operations
Sreedhar Chowdam
 
DBMS Notes selection projection aggregate
DBMS Notes selection projection aggregateDBMS Notes selection projection aggregate
DBMS Notes selection projection aggregate
Sreedhar Chowdam
 
Database management systems Lecture Notes
Database management systems Lecture NotesDatabase management systems Lecture Notes
Database management systems Lecture Notes
Sreedhar Chowdam
 
Advanced Data Structures & Algorithm Analysi
Advanced Data Structures & Algorithm AnalysiAdvanced Data Structures & Algorithm Analysi
Advanced Data Structures & Algorithm Analysi
Sreedhar Chowdam
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
Sreedhar Chowdam
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)
Sreedhar Chowdam
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCP
Sreedhar Chowdam
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
Sreedhar Chowdam
 
DCCN Unit 1.pdf
DCCN Unit 1.pdfDCCN Unit 1.pdf
DCCN Unit 1.pdf
Sreedhar Chowdam
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer Networks
Sreedhar Chowdam
 
PPS Notes Unit 5.pdf
PPS Notes Unit 5.pdfPPS Notes Unit 5.pdf
PPS Notes Unit 5.pdf
Sreedhar Chowdam
 
Big Data Analytics Part2
Big Data Analytics Part2Big Data Analytics Part2
Big Data Analytics Part2
Sreedhar Chowdam
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
Sreedhar Chowdam
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
Sreedhar Chowdam
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture Notes
Sreedhar Chowdam
 
Big Data Analytics
Big Data AnalyticsBig Data Analytics
Big Data Analytics
Sreedhar Chowdam
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021
Sreedhar Chowdam
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01
Sreedhar Chowdam
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library database
Sreedhar Chowdam
 
DBMS Nested & Sub Queries Set operations
DBMS Nested & Sub Queries Set operationsDBMS Nested & Sub Queries Set operations
DBMS Nested & Sub Queries Set operations
Sreedhar Chowdam
 
DBMS Notes selection projection aggregate
DBMS Notes selection projection aggregateDBMS Notes selection projection aggregate
DBMS Notes selection projection aggregate
Sreedhar Chowdam
 
Database management systems Lecture Notes
Database management systems Lecture NotesDatabase management systems Lecture Notes
Database management systems Lecture Notes
Sreedhar Chowdam
 
Advanced Data Structures & Algorithm Analysi
Advanced Data Structures & Algorithm AnalysiAdvanced Data Structures & Algorithm Analysi
Advanced Data Structures & Algorithm Analysi
Sreedhar Chowdam
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
Sreedhar Chowdam
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)
Sreedhar Chowdam
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCP
Sreedhar Chowdam
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
Sreedhar Chowdam
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer Networks
Sreedhar Chowdam
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
Sreedhar Chowdam
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
Sreedhar Chowdam
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture Notes
Sreedhar Chowdam
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021
Sreedhar Chowdam
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01
Sreedhar Chowdam
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library database
Sreedhar Chowdam
 
Ad

Recently uploaded (20)

02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Understanding Amplitude Modulation : A Guide
Understanding Amplitude Modulation : A GuideUnderstanding Amplitude Modulation : A Guide
Understanding Amplitude Modulation : A Guide
CircuitDigest
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
grade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quizgrade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quiz
norfapangolima
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Understanding Amplitude Modulation : A Guide
Understanding Amplitude Modulation : A GuideUnderstanding Amplitude Modulation : A Guide
Understanding Amplitude Modulation : A Guide
CircuitDigest
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...4th International Conference on Computer Science and Information Technology (...
4th International Conference on Computer Science and Information Technology (...
ijait
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
grade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quizgrade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quiz
norfapangolima
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 

Python Programming: Lists, Modules, Exceptions

  • 1. Lists  Creating Lists,  Accessing the Elements of a List,  Negative List Indices,  List Slicing [Start: end], List Slicing with Step Size,  Python Inbuilt Functions for Lists,  The List Operator, List Comprehensions,  List Methods, List and Strings, Splitting a String in List,  Passing List to a Function, Returning List from a Function. Prepared by Dr. C. Sreedhar
  • 2. # Lists are used to store multiple items in a single variable. # List items can be of similiar items, different items,duplicates list1 = ["cse", "cst", "csbs"] list2 = [10, 50, 60, 80, 40] list3 = [True, False, False] list4 = ["cse4a","cse4b","cse4a","ece"] print(list1) print(list2) print(list3) print(list4[1]) ['cse', 'cst', 'csbs'] [10, 50, 60, 80, 40] [True, False, False] cse4b Prepared by Dr. C. Sreedhar
  • 3. # Accept list items from user uslng list() constructor l1=input(list()) print(l1) # Access the elements using index [ ] operator list4 = ["cse4a","cse4b","cse4a","ece"] print(list4[2]) cse4b # Slicing the list using #Name_of_Variable_of_a_List[Start_Index: End_Index] list4 = ["cse4a","cse4b","cse4a","ece"] ['cse4b', 'cse4a'] Prepared by Dr. C. Sreedhar
  • 4. Prepared by Dr. C. Sreedhar
  • 5. Lists in python  Lists are used to store multiple items in a single variable.  List items can be of any data type. Example:  list1 = ["cse", "cst", "csbs"]  list2 = [10, 50, 60, 80, 40]  list3 = [True, False, False]  List allows duplicates. Example:  cse4a = ["ram", "shyam", "ram", "sree", "dennis"]  print(cse4a)  List allows different data types. Example Prepared by Dr. C. Sreedhar
  • 6. Creating a list with w/o using constructor of the list class  Lists can be created in Python with constructor and w/o constructor Using list Constructor  Create an empty list. L1 = list();  Create a list with any three integer elements, such as 10, 20 and 30. L2 = list([10,20,30])  Create a list with three string elements, such as “Apple”, “Banana” and “Grapes”. L3 = list([“Apple”,”Banana”,”Grapes”])  Create a list using inbuilt range() function. L4 = list(range(0,6))  Create a list with inbuilt characters X, Y and Z. L5=list(“xyz”)  Create a list with any three integer elements, such as 10, 20 and 30. L1=[10,20,30] Prepared by Dr. C. Sreedhar
  • 7. ACCESSING THE ELEMENTS OF A LIST  index [] operator is used to access them. The syntax is: Name_of_Variable_of_a_List[index]  L1=([10,20,30,40,50]) >>> List1=[10,20,30,40,50,60] >>> List1[-3] Output 40 Prepared by Dr. C. Sreedhar
  • 8. LIST SLICING [START: END]  Name_of_Variable_of_a_List[Start_Index: End_Index] >>> L1=([10,20,30,40,50]) >>> L1[1:4] Output 20,30,40 >>> L1[2:5] Output Prepared by Dr. C. Sreedhar
  • 9. LIST SLICING WITH STEP SIZE  List_Name[Start_Index:End_Index:Step_Size] >>>MyList1=[“CSE”,1,”CST”,2,”ECE”,3,”EEE”] >>>New_List1=MyList1[0:6:2] print(New_List1) Output [‘CSE’, ‘CST’, ‘ECE’] >>> List1=[“Python”,450,”C”,300,”,C++”,670] >>> List1[0:6:3] Output Prepared by Dr. C. Sreedhar
  • 10. PYTHON INBUILT FUNCTIONS FOR LIST Prepared by Dr. C. Sreedhar
  • 11.  + Operator: The concatenation operator is used to join two lists.  a=[1,2,3] b=[4,5,6] a+b # [1, 2, 3, 4, 5, 6]  * Operator: The multiplication operator is used to replicate the elements of a list.  List1=[10,20] List2=[20,30] List3=2*List1 #[10, 20, 10, 20]  in Operator: The in operator used to determine whether an element is in a list. It returns True if the element is present and False if the element is absent in the list.  List1= [10,20]  >>> 40 in List1  False LIST OPERATOR Prepared by Dr. C. Sreedhar
  • 12. LIST OPERATOR  isOperator  >>> A=’Microsoft’  >>> B=’Microsoft’  >>> A is B  True  >>> A=[‘A’,’B’,’C’]  >>> B=[‘A’,’B’,’C’]  >>> A is B #Check if two lists refer to the same Object  False Prepared by Dr. C. Sreedhar
  • 13. del Operator Lst=[10,20,30,40,50,60,70] >>> del Lst[2] #Removes 3rd element from the List >>> Lst [10, 20, 40, 50, 60, 70] Lst=[10,20,30,40,50,60,70] >>> del Lst[-1] >>> Lst #Removes last element from the List [10, 20, 30, 40, 50, 60] >>> Lst=[10,20,30,40,50,60,70] >>> del Lst[2:5] #Removes element from index position 2 to 4 >>> Lst [10, 20, 60, 70] >>> Lst=[10,20,30,40,50,60,70] >>> del Lst[:] #Removes all the element from the List >>> Lst []s Prepared by Dr. C. Sreedhar
  • 14. LIST COMPREHENSIONS  List comprehension is used to create a new list from existing sequences Normal Code List1= [10, 20, 30, 40, 50] for i in range(0,len(List1)): List1[i]=List1[i]+5 # [15, 25, 35, 45, 55] Using List Comprehension List1= [10,20,30,40,50] List1= [x+10 for x in List1] # [20, 30, 40, 50, 60] Prepared by Dr. C. Sreedhar
  • 15. Unit 4 • Modules: Reusing Code with Modules and Packages, Understanding Python Modules, Everyday Module Usage, Advanced Module Behavior, Combining Modules into Packages • Exceptions: When Something Goes Wrong, Classes of Exceptions, A Final Note on Pythonic Exception Handling. • File Handling: Need of File Handling, Text Input and Output, The seek() Function, Binary Files, Accessing and Manipulating Files and Directories on a Disk. Prepared by Dr. C. Sreedhar
  • 16. • os – os.getcwd() – os.fspath(path) – os.getlogin() • ipaddress: –ipaddress.IPv4Address(address) –ipaddress.IPv6Address(address) • math: – math.factorial(x) – math.gcd(n1,n2) – math.lcm(n1,n2) – math.trunc(x) – math.pow(x, y) – math.pi • random: – random.randint(a,b) – random.uniform(a,b) • time: – time.clock_gettime() – time.clock_gettime_ns() Module: Builtin Modules Prepared by Dr. C. Sreedhar
  • 17. Modules: Create and import • 1. Open Python IDLE (Start --> Python IDLE) • 2. File --> New File • 3. ---- type the following code---- def greeting(name): print("Hello, " + name) • 4. Save with module1.py (in Desktop or any folder) • 5. Pyhton IDLE ==> File --> New File • 6. ------ type the following code ---- import module1 module1.greeting("CSE4A") • 7. Save as runmodule.py (in Desktop or any folder) • 8. In Python IDLE, click on Run --> Run Module from <module_name> import * from <module_name> import <name> as <alt_name> Prepared by Dr. C. Sreedhar
  • 19. In python, the inbuilt __import__() function helps to import modules in runtime Syntax: __import__(name, globals, locals, fromlist, level) Ex: math_score = __import__('math', globals(), locals(), [], 0) print(math_score.fabs(17.4)) Prepared by Dr. C. Sreedhar
  • 20. Package • A package is basically a directory with Python file and file with the extension as _init_.py. • Steps to create package: – create a package (folder). The name of package, say, My _ First _ Package – Create _ init _ .py file inside the created package My_First_Package. – The directory should contain a file named _init_.py. This file can be empty or it may contain valid Python code. – create two different .py files, i.e. a.py and b.py with code a.py def call_A(): print(“This is first program”) b.py def call_B(): print(“This is second”) >>> My_First_Package.a.call_A() This is first program >>> My_First_Package.b.call_B() This is second _init_.py import My_First_Package.a import My_First_Package.b Prepared by Dr. C. Sreedhar
  • 21. # GPREC/CSBS/__init__.py (Empty file) # GPREC/CSBS/csbs4sem.py print("In CSBS branch") # GPREC/CSE/__init__.py from . import cse4a from . import cse4b # GPREC/CSE/cse4a.py print("In CSE 4A Class") # GPREC/CSE/cse4b.py print("In CSE 4B Class") # GPREC/CSE/cse4c.py print("In CSE 4C Class") # world/__init__.py from . import CSBS from GPREC import CSE import GPREC.CSE.cse4a from GPREC.CSE import cse4b Prepared by Dr. C. Sreedhar
  • 22. Exceptions • An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. • Exception: Base class for all exceptions • ArithmeticError: Base class for all errors that occur for numeric calculation. • OverflowError: Raised when a calculation exceeds maximum limit for a numeric type. • FloatingPointError: Raised when a floating point calculation fails. • ZeroDivisionError: Raised when division or modulo by zero takes place for numeric • AttributeError: Raised in case of failure of attribute reference or assignment. • EOFError: Raised when end of file is reached. • ImportError: Raised when an import statement fails. • IndexError: Raised when an index is not found in a sequence. • EnvironmentError: Base class for all exceptions that occur outside Python environment. • SyntaxError: Raised when there is an error in Python syntax. • TypeError: Raised when an operation is attempted that is invalid for specified data type. Prepared by Dr. C. Sreedhar
  • 24. try: num1,num2 = eval(input("Enter two numbers,separated by a comma:")) result = num1 / num2 print("Result is", result) except ZeroDivisionError: print("Division by zero is error !!") except SyntaxError: print("Comma is missing. Enter nos separated by comma like this 1, 2") except: print("Wrong input") else: print("No exceptions") finally: print("This will execute no matter what“) Prepared by Dr. C. Sreedhar
  • 25. try: a = [1, 2, 3] print (a[3]) except LookupError: print ("Index out of bound error.") else: print ("Success") Prepared by Dr. C. Sreedhar
  • 26. try: age= int(input()) assert (age>0 and age<100) # True: moves to the next line ie., print age; False: returns Assertion Error except AssertionError: print("Not valid age.") except: print("Invalid data entered") else: print("Age is:",age) Prepared by Dr. C. Sreedhar
  • 27. try: age= int(input("Enter your age:")) if age<0: raise ValueError except ValueError: print("Age cannot be less than zero.") else: print("Age is:",age) Prepared by Dr. C. Sreedhar
  • 28. Format: <file variable> = open(<file name>, "r") Example: filename = input("Enter name of input file: ") inputFile = open(filename, "r") Python File handling Prepared by Dr. C. Sreedhar
  • 29. Modes Description r Opens a file for reading only, default mode. rb Opens a file for reading only in binary format. r+ Opens a file for both reading and writing rb+ Opens a file for both reading and writing in binary format w Opens a file for writing only. Overwrites the file if the file exists. Wb Opens a file for writing only in binary format. Overwrites the file if the file exists w+ Opens a file for both writing and reading, Overwrites file if file exists Prepared by Dr. C. Sreedhar
  • 30. Example: file2 = open(“cse4a.txt", "wb") print ("Name of the file: ", file2.name) print ("Closed or not : ", file2.closed) print ("Opening mode : ", file2.mode) This would produce following result: Name of the file: foo.txt Closed or not : False Opening mode : wb Prepared by Dr. C. Sreedhar
  • 31. Reading contents from file inputFileName = input("Enter name of input file:") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") for line in inputFile: sys.stdout.write(line) inputFile.close() print("Completed reading of file", inputFileName) Prepared by Dr. C. Sreedhar
  • 32. Alternate way to read contents from file inputFileName = input ("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") line = inputFile.readline() while (line != ""): sys.stdout.write(line) line = inputFile.readline() inputFile.close() print("Completed reading of file", inputFileName) Prepared by Dr. C. Sreedhar
  • 33. Writing contents fo = open(“cse4a.txt", "wb") fo.write("Welcome to CSE4A n"); fo.close() Prepared by Dr. C. Sreedhar
  • 34. Writing contents from one file into another inputFileName = input("Enter file name to read grades from: ") outputFileName = input("output filename to write GPA's to: ") inputFile = open(inputFileName, "r") outputFile = open(outputFileName, "w") print("Opening file", inputFileName, " for reading.") print("Opening file", outputFileName, " for writing.") gpa = 0 Prepared by Dr. C. Sreedhar
  • 35. seek() • seek() function is used to change the position of the File Handle to a given specific position. Prepared by Dr. C. Sreedhar
  • 36. Unit 5 Object-Oriented Programming: • Class, Objects and Inheritance: Defining Classes, The Selfparameter and Adding Methods to a Class, • Display Class Attributes and Methods, Special Class Attributes, Accessibility, The __init__ Method (Constructor), • Passing an Object as Parameter to a Method, __del__() (Destructor Method), Class Membership Tests, • Method Overloading, Operator Overloading, Inheritance, The Object Class. Prepared by Dr. C. Sreedhar
  • 37. Class and attributes class Example : x = 10 print(Example.x) class Example: x = 10 y = 20 print(Example.x) print(Example.y) Prepared by Dr. C. Sreedhar
  • 38. Class and method class Example: x=10 y=20 def show(obj): print("x=",obj.x) print("y=",obj.y) Example.show=classmethod(Example.show) Example.show() Prepared by Dr. C. Sreedhar
  • 39. Constructor class Student: count = 0 def __init__(self): Student.count = Student.count + 1 s1=Student() s2=Student() s3=Student() print("Total students:",Student.count) Prepared by Dr. C. Sreedhar
  • 40. Class and Object class Student: def __init__(self, name, percentage): self.name = name self.percentage = percentage def show(self): print("Name:", self.name,“percentage:", self.percentage) stud = Student("Sreedhar", 90) stud.show() Prepared by Dr. C. Sreedhar
  • 41. Data encapsulation class Employee: def __init__(self, name, empid): self.name = name self.empid = empid def show(self): print("Name: ", self.name, "and ID:", self.empid) E = Employee("Sreedhar", 6666) print(E.name) print(E.empid) Prepared by Dr. C. Sreedhar
  • 42. Class attributes class MyClass(object): var = 10 def set_val(self): self.b = 100 ob1 = MyClass() print(ob1.var) # This will fetch the class attribute 10. ob1.set_val() print(ob1.b) # This will fetch the class attribute 100 Prepared by Dr. C. Sreedhar
  • 43. Class constructor: Example class gprecclass: def __init__ (self, section): # self allows to attach parameter to the class self.section =section p = gprecclass("CSE4A") print(p.section) Prepared by Dr. C. Sreedhar
  • 44. __init__ method: Constructor class MyNum(object): def __init__(self): print("Calling __init__() constructor!n") self.val = 0 def increment(self): self.val = self.val + 1 print(self.val) dd = MyNum() dd.increment() # will print 1 dd.increment() # will print 2 Prepared by Dr. C. Sreedhar
  • 45. Constructor class Rectangle(object): def __init__(self, l, w): self.length = l self.width = w def area(self): return self.length*self.width a = Rectangle(2,10) print(a.area()) Prepared by Dr. C. Sreedhar
  • 46. Methods class Circle: pi = 3.14 def __init__(self, radius=1): self.radius = radius self.area = radius * radius * Circle.pi def setRadius(self, new_radius): self.radius = new_radius self.area = new_radius * new_radius * self.pi def getCircumference(self): return self.radius * self.pi * 2 c = Circle() print('Radius is: ',c.radius) print('Area is: ',c.area) print('Circumference is: ',c.getCircumference()) Prepared by Dr. C. Sreedhar
  • 47. Class and methods class Subject: def __init__(self, name, id): self.id = id self.name = name def display(self): print("Subject ID:%d Name:%s”%(self.id, self.name)) ppy = Subject("Python Programming", 101) ds = Subject("Data Structures", 102) ppy.display() ds.display() Prepared by Dr. C. Sreedhar
  • 48. Public access modifier class Bank: def __init__(self, name, pin): # public data members self.bankname = name self.bankpin = pin # public member function def displaypin(self): # accessing public data member print("Pincode: ", self.bankpin) obj = Bank("Union Bank", 518007) print("Bank Name: ", obj.bankname) obj.displaypin() Prepared by Dr. C. Sreedhar
  • 49. Private specifier class Bank: bankname="SBI" __custname = None # privatemember __custage = 20 __custbranch = None def __init__(self, name, age, branch): self.__custname = name self.__custage = age self.__custbranch = branch # private member function def __displayDetails(self): print("Customer Name: ", self.__custname) print("Customer Age: ", self.__custage) print("Cust Branch: ", self.__custbranch) # public member function def accessPrivateFunction(self): # accessing private member function self.__displayDetails() obj = Bank("Sree", 25, "SN Colony") print(obj.bankname) obj.accessPrivateFunction() Prepared by Dr. C. Sreedhar
  • 50. Inheritance class Base: def func1(self): print('This is Base class') class Derived(Base): def func2(self): print('This is Derived class') obj = Derived() obj.func1() obj.func2() Prepared by Dr. C. Sreedhar
  • 51. Inheritance class Date(object): def get_date(self): print("2022-05-3") class Time(Date): def get_time(self): print("14:10:00") dt = Date() dt.get_date() print("----------“) tm = Time() tm.get_time() tm.get_date() Prepared by Dr. C. Sreedhar
  • 52. Multiple Inheritance class A(object): def method1(self): print("doing this in A") class B(A): pass class C(object): def method1(self): print("doing this in C") class D(B, C): pass d_instance = D() d_instance.method1() print("nPrint the Method Resolution Order") print(D.mro()) Prepared by Dr. C. Sreedhar
  • 53. Method Overloading class Person: def M1(self, name=None): if name is not None: print('Name: ' + name) else: print('Default name ') obj = Person() obj.M1() obj.M1('ABCDEF‘) Prepared by Dr. C. Sreedhar
  • 54. Method Overloading class A: def __init__(self, a): self.a = a # adding two objects def __add__(self, o): return self.a + o.a ob1 = A(10) ob2 = A(30) ob3 = A("CSE4A") ob4 = A(" ECE4A") print(ob1 + ob2) print(ob3 + ob4) Prepared by Dr. C. Sreedhar
  • 55. Operator Overloading import math class Circle: def __init__(self, radius): self.__radius = radius def setRadius(self, radius): self.__radius = radius def getRadius(self): return self.__radius def area(self): return math.pi * self.__radius ** 2 def __add__(self, circle_object): return Circle(self.__radius + circle_object.__radius) def __lt__(self, circle_object): return (self.__radius < circle_object.__radius) def __gt__(self, circle_object): return (self.__radius > circle_object.__radius) def __str__(self): return "Circle area = " + str(self.area()) c1 = Circle(20) c2 = Circle(30) c3 = c1 + c2 print(c1.getRadius()) print(c2.getRadius()) print(c3.getRadius()) print(c1 < c2) print(c3 > c2) print(str(c1)) print(str(c2)) print(str(c3)) Prepared by Dr. C. Sreedhar