Module 1 Python Basics - Programs
Module 1 Python Basics - Programs
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:
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))
2. List
# empty list
my_list = []
my_list=[]
mylist=[3,"Hello", 5.4]
print(mylist)
print(mylist[1])
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
extend() add items of lists and other iterables to the end of the list
7. Tuple
# Empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
9. string
10. 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)
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))
for i in range(10):
print('Factorial of {} is {}'.format(i, factorial(i)))
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)
lst=[10,23,45,67,34,99]
lst1=list(filter(lambda x: (x%2==0),lst))
print(lst1)
lst=[10,23,45,67,34,99]
lst1=list(map(squares,lst))
print(lst1)
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
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())
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:
finally:
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")
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')
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()
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)
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)
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)