Module 1 Python basics
Data types in python, Operators in python, Input and Output, Control statement, Arrays in
python, String and Character in python, Functions, List and Tuples, Dictionaries Exception,
Introduction to OOP, Classes, Objects, Interfaces, Inheritance
Program:
Data types in python
1. Integer, float, complex
num1 = 5
print(num1, 'is of type', type(num1))
num2 = 5.42
print(num2, 'is of type', type(num2))
num3 = 8+2j
print(num3, 'is of type', type(num3))
5 is of type <class 'int'>
5.42 is of type <class 'float'>
(8+2j) is of type <class 'complex'>
2. List
3. # A list with 3 integers
4. numbers = [1, 2, 5]
5.
6. print(numbers)
7.
8. # Output: [1, 2, 5]
3. List with mixed data types
# empty list
my_list = []
# list with mixed data types
my_list = [1, "Hello", 3.4]
4. accessing an element from the list
my_list=[]
mylist=[3,"Hello", 5.4]
print(mylist)
print(mylist[1])
5. adding or deleting element from a list
my_list=[]
mylist=[3,"Hello", 5.4]
print(mylist)
mylist.append(10)
print(mylist)
del mylist[1]
print(mylist)
6. extending a list
my_list=[]
mylist=[3,"Hello", 5.4]
print(mylist)
part2=[2, 4, "p", 5.6]
mylist.extend(part2)
print(mylist)
7. slicing a list
my_list=[]
mylist=[3,"Hello", 5.4]
print(mylist)
mylist.append(10)
print(mylist)
print(mylist[1:3])
Method Description
append() add an item to the end of the list
extend() add items of lists and other iterables to the end of the list
insert() inserts an item at the specified index
remove() removes item present at the given index
pop() returns and removes item present at the given index
clear() removes all items from the list
index() returns the index of the first matched item
count() returns the count of the specified item in the list
sort() sort the list in ascending/descending order
reverse() reverses the item of the list
copy() returns the shallow copy of the list
7. Tuple
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
9. string
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"
# compare str1 and str2
print(str1 == str2)
# compare str1 and str3
print(str1 == str3)
10. Set
11. # create a set of integer type
12. student_id = {112, 114, 116, 118, 115}
13. print('Student ID:', student_id)
14.
15. # create a set of string type
16. vowel_letters = {'a', 'e', 'i', 'o', 'u'}
17. print('Vowel Letters:', vowel_letters)
18.
19. # create a set of mixed data types
20. mixed_set = {'Hello', 101, -2, 'Bye'}
21. print('Set of mixed data types:', mixed_set)
11. Dictionary
numbers={1:"one",2:"Two", 3:"three", 4:"Four"}
print(numbers)
numbers[5]="Five"
print(numbers)
del numbers[3]
print(numbers)
12. Boolean
x=5
y = 10
print(bool(x==y))
z=5
print(bool(x==z))
13. Logical
x=1
y=2
z=3
if (x<y or y<z):
print('yes')
else:
print('No')
print(not x)
14 identity Operator
x=5
y=5
print(x is y)
15. Membership operator
list = [10, 20, 30, 40, 50]
x=20
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
16. Functions
def add(num1, num2):
num3 = num1 + num2
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print("The addition of {} and {} results {}".format(num1, num2, ans))
Recursive function Pb 26 Pg 262
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
for i in range(10):
print('Factorial of {} is {}'.format(i, factorial(i)))
Anonymous function lambda Pb 28 Pg 265
f= lambda x: x*x
value=f(5)
print('Square of 5 is', value)
filter() is use to filter out elements from a sequence depending on the result of a function
def is_even(x):
if x%2==0:
return True
else:
return False
lst=[10,23,45,67,34,99]
lst1=list(filter(is_even,lst))
print(lst1)
Same thing using Lambda
lst=[10,23,45,67,34,99]
lst1=list(filter(lambda x: (x%2==0),lst))
print(lst1)
map() function acts on each element and changes the element
def squares(x):
return x*x
lst=[10,23,45,67,34,99]
lst1=list(map(squares,lst))
print(lst1)
same thing with lambda
lst=[10,23,45,67,34,99]
lst1=list(map(lambda x: x*x,lst))
print(lst1)
reduce() will reduce the sequence to a single value as per the function supplied
from functools import *
lst=[1, 2, 3, 4, 5]
result=reduce(lambda x,y: x*y, lst)
print(result)
Dictionaries
Pb 2 Pg 325
dict={'Name': 'Vidya', 'Id':200, 'Salary': 10000}
print('Keys in the dictionary are =', dict.keys())
print('Values in the dictionary are= ', dict.values())
print('Items in the dictionary are= ', dict.items())
loop for dictionary
colors={'r': 'Red', 'b':'Blue', 'g': 'Green', 'w': 'White'}
for k in colors:
print(k)
for k in colors:
print(colors[k])
for k,v in colors.items():
print('Key={}, Value={}'.format(k,v))
passing dictionary to function pb. 11 Pg 335
def func(dict):
for k,v in dict.items():
print('Key={}, Value={}'.format(k,v))
colors={'10': 'Red', '2':'Blue', '13': 'Green', '48': 'White'}
func(colors)
syntax error
amount = 10000
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
Exceptions
marks = 10000
a = marks / 0
print(a)
Exception handling
marks = 10000
try:
a = marks / 0
print(a)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
marks = 10000
try:
a = marks / 0
print(a)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
finally:
print('This is always executed')
Exception type error
x=5
y = "hello"
z=x+y
Handling type error
x=5
y = "hello"
try:
z=x+y
except TypeError:
print("Error: cannot add an int and a str")
Class, instance variable, instance, object, method
Difference between instance and class variable
Instance variable is available for the current instance only
Example
class SE:
def __init__(self, name, roll_no):
# This is the constructor method that is called when creating a new Person object
# It takes two parameters, name and age, and initializes them as attributes of the object
self.name = name
self.roll_no = roll_no
def greet(self):
# This is a method of the Person class that prints a greeting message
print("Hello, my name is " + self.name)
s1=SE('ABC',1)
s2=SE('EFG',2)
print(s1.name)
print(s2.roll_no)
class Sample:
def __init__(self):
self.x=10
def modify(self):
self.x+=1
s1=Sample()
s2=Sample()
print('x in s1 = ', s1.x)
print('x in s2 = ', s2.x)
s1.modify()
print('x in s1 = ', s1.x)
print('x in s2 = ', s2.x)
Class variable
class Sample:
x=10
@classmethod
def modify(cls):
cls.x+=1
s1=Sample()
s2=Sample()
print('x in s1 = ', s1.x)
print('x in s2 = ', s2.x)
s1.modify()
print('x in s1 = ', s1.x)
print('x in s2 = ', s2.x)
Class Method
class Person:
person_name = "Name" #Class Variable
@classmethod
def modify(cls):
cls.person_name="New_Name"
n1 = Person()
print(n1.person_name)
n2=Person()
print(n2.person_name)
n1.modify()
print(n1.person_name)
print(n2.person_name)
Multiple Class
class MyClass1:
def __init__(self):
MyClass1.var1=10
MyClass1.var2=20
s=0
def sum(self):
s=MyClass1.var1+MyClass1.var2
return s
class MyClass2:
def __init__(self):
MyClass2.var1=50
def display(self):
print(MyClass2.var1)
obj1=MyClass1()
print('Method of MyClass1')
sum1=obj1.sum()
print(sum1)
print('Method of MyClass2')
obj2=MyClass2()
obj2.display()
class Student:
def __init__(self,n='',m=0):
self.name=name
self.marks=m
def grade_calculation(self):
print('Student Name:', self.name)
if(self.marks>60):
print('The grade is A')
elif(self.marks>50):
print('The grade is B')
elif(self.marks>40):
print('The grade is C')
else:
print('Fail')
name=input('Enter Name: ')
marks=int(input('Enter MArks:'))
s=Student(name,marks)
s.grade_calculation()
static method : is used when we want to do some processing related to class but we do not
need class or its instances to perform any tasks
class Myclass:
n=0
def __init__(self):
Myclass.n+=1
@staticmethod
def No_of_object():
print('The number of objects is', Myclass.n)
obj1=Myclass()
obj2=Myclass()
obj3=Myclass()
Myclass.No_of_object()
Create class within a class:
class Person:
def __init__(self):
self.name='ABC'
self.db=self.DoB()
def display(self):
print('Name = ',self.name)
class DoB:
def __init__(self):
self.dd=10
self.mm=11
self.yy=2022
def display(self):
print('Date of Birth is {}/{}/{}'.format(self.dd,self.mm,self.yy))
p=Person()
p.display()
x=Person().DoB()
x.display()
Inheritance
teacher.py
class Teacher:
def setid(self,id):
self.id=id
def getid(self):
return self.id
def setname(self,name):
self.name=name
def getname(self):
return self.name
def setsal(self,sal):
self.sal=sal
def getsal(self):
return self.sal
main.py
from teacher import Teacher
t=Teacher()
t.setid(10)
t.setname('ABC')
t.setsal(1000.50)
print('ID is ', t.getid())
print('Name is ', t.getname())
print('Sal is',t.getsal())
student.py
class Student:
def setid(self,id):
self.id=id
def getid(self):
return self.id
def setname(self,name):
self.name=name
def getname(self):
return self.name
def setmarks(self,marks):
self.marks=marks
def getmarks(self):
return self.marks
main.py
from student import Student
s=Student()
s.setid(20)
s.setname('XYZ')
s.setmarks(85)
print('ID is ', s.getid())
print('Name is ', s.getname())
print('Marks is',s.getmarks())
Student class derived from Teacher class
Original class (here teacher class) is called super class/base class and the student class is
called sub-class or derived class
Creating Student class from Teacher class is called inheritance
from teacher import Teacher
class Student(Teacher):
def setmarks(self,marks):
self.marks=marks
def getmarks(self):
return self.marks
s=Student()
s.setid(20)
s.setname('XYZ')
s.setmarks(85)
print('ID is ', s.getid())
print('Name is ', s.getname())
print('Marks is',s.getmarks())