Advanced Python Practical Lab Lab code:ACSE0252 Session: 2020-21
Advanced Python Practical Lab Lab code:ACSE0252 Session: 2020-21
Submitted by : Submitted to :
Name : Ajay Prasad Mr. Harsh Vardhan Mishra
Branch : CSE(AIML)
Section : AIML-C
Roll No : 2001331530022
List Of Programs
SN.NO: NAME OF PROGRAMS PERFORMED IN DATE OF DATE OF REMARKS
ONLINE LAB
EXPERIMEN SUBMISSION
T
Programs
01) Write a program illustrating class definition and accessing class members
Code:
class Student:
var="class variable"
def __init__(self):
self.name="student"
self.roll_no=12345
obj=Student()
print(obj.var)
print(obj.name)
print(obj.roll_no)
Output:1
class variable
student
12345
02) Write a program to implement default constructor, parameterized constructor, and destructor.
Code:
class Course1:
def __init__(self):
self.name="python"
def __del__(self):
print("object distoryed")
class Course2:
def __init__(self,name):
self.name=name
def __del__(self):
print("object of course2 is destoryed")
python=Course1()
advance=Course2("Advance python")
print(python.name)
print(advance.name)
Output:2
python
Advance python
03) Create a Python class named Rectangle constructed by a length and width.
#a.Create a method called area which will compute the area of a rectangle.
Code:
class Rectangle:
def __init__(self,l,w):
self.length=l
self.width=w
def area(self):
return self.length*self.width
a=int(input("Enter length of rectangle: "))
b=int(input("Enter width of rectangle: "))
rectangle=Rectangle(a,b)
print("Area of rectangle: ",rectangle.area())
Output:3
Enter length of rectangle: 12
04) Create a class called Numbers, which has a single class attribute called MULTIPLIER, and a constructor which
takes the parameters x and y (these should all be numbers).
a.Write an instance method called add which returns the sum of the attributes x and y.
b.Write a class method called multiply, which takes a single number parameter a and returns the product of a and
MULTIPLIER.
c.Write a static method called subtract, which takes two number parameters, b and c, and returns b - c.
d.Write a method called value which returns a tuple containing the values of x and y.
Code:
class Numbers:
MULTIPLIER=int(input("Enter multiplier :"))
def __init__(self,x,y):
self.x=x
self.y=y
def add(self):
return self.x+self.y
@classmethod
def multiply(cls,a):
return a*cls.MULTIPLIER
@staticmethod
def subtract(b,c):
return b-c
def value(self):
return self.x , self.y
num=Numbers(2,5)
print("instance method :",num.add())
print("class method :",Numbers.multiply(5))
print("staticmethod :",num.subtract(7,2))
print("instance method :",num.value())
Output:4
Enter multiplier :2
instance method : 7
class method : 10
staticmethod : 5
05) Create a class named as Student to store the name and marks in three subjects. Use List to store the marks.
a.Write an instance method called compute to compute total marks and average marks of a student.
Code:
class Student:
def __init__(self):
self.name=input("Enter name of student :")
self.marks=input("Enter three subject marks separated by space :").split()
def compute(self):
self.total=0
for i in self.marks:
self.total+=int(i)
self.avg=self.total/3
def display(self):
print("Name :",self.name)
print("Total marks :",self.total)
print("Average marks :",self.avg)
stud=Student()
stud.compute()
stud.display()
Output:5
Enter name of student :Ravi
Name : Ravi
Total marks : 79
06) Create a class Employee that keeps a track of the number of employees in an organization and also stores their
name, designation and salary details.
a. Write a method called getdata to take input (name, designation, salary) from user.
b. Write a method called average to find average salary of all the employees in the organization.
c. Write a method called display to print all the information of an employee.
Code:
class Employee:
total_sal=0
count=0
def getdata (self):
print("Enter details of employee: ",Employee.count+1)
self.desi=input("Enter designation")
self.name=input("Enter name")
self.salary=int(input("enter salary"))
Employee.count+=1
@classmethod
def avg(cls):
return cls.total_sal/cls.count
def display(self):
print(f"{self.name}\t{self.desi}\t{self.salary}")
e1=Employee()
e2=Employee()
e3=Employee()
for i in(e1,e2,e3):
i.getdata()
print("details of all emplyees are")
print("Name\tdesi\tsalary")
for i in(e1,e2,e3):
i.display()
print("average salary is ",Employee.avg())
Output:6
Enter details of employee: 1
Enter designation Hello
Enter name Ravi
enter salary 200000
Enter details of employee: 2
Enter designation Computer
Enter name Anand
enter salary 30000
Enter details of employee: 3
Enter designation Himanshu
Enter name Prabhas
enter salary 40000
details of all emplyees are
Name desi salary
Ravi Hello 200000
Anand Computer 30000
Prabhas Technical 40000
average salary is 0.0
07) Create a Python class named Circle constructed by a radius. Use a class variable to define the value of constant
PI.
a. Write two methods to be named as area and circum to compute the area and the perimeter of a circle respectively
by using class variable PI.
Code:
class Circle:
pi=3.14
def __init__(self):
self.radius=int(input("Enter radius of circle :"))
def area(self):
self.area=Circle.pi*self.radius**2
def perimeter(self):
self.peri=2*Circle.pi*self.radius
def display(self):
print("Area :",self.area)
print("Perimeter :",self.peri)
cir=Circle()
cir.area()
cir.perimeter()
cir.display()
Output:7
Enter radius of circle :5
Area : 78.5
Perimeter : 31.400000000000002
08) Create a class called String that stores a string and all its status details such as number of uppercase letters,
lowercase letters, vowels ,consonants and space in instance variables.
Output:8
Enter the string :Ravi
string is : Ravi
count of uppercase is : 1
count of lowercasr is : 3
count of vowels is : 2
count of consonants is : 2
count of space is : 0
09) Write a program that has a class called Fraction with attributes numerator and denominator.
Code:
class Fraction:
def __init__(self):
self.num=None
self.deno=None
def getdata(self):
self.num=int(input("Enter numerator :"))
self.deno=int(input("Enter denominator :"))
def simplify(self):
gcd=self.GCD()
self.num//=gcd
self.deno//=gcd
def GCD(self):
x=self.num
y=self.deno
rem=x%y
while rem:
x=y
y=rem
rem=x%y
return y
def show(self):
print(f"{self.num}/{self.deno}")
f1=Fraction()
f1.getdata()
print("Your fraction number is :",f1.show())
f1.simplify()
print("simplified form of fraction is")
f1.show()
Output:09
Enter numerator :55
55/60
11/12
10)Write a program that has a class Numbers with a list as an instance variable.
b. Write a class method called find_max to find and print largest value in the list.
Code:
class Numbers:
def __init__(self):
self.num=[]
def insert_method(self,n):
print("Insert element in the list")
for i in range(n):
self.num.append(int(input()))
@classmethod
def find_max(cls,self):
max=None
for i in self.num:
if max is None or max<i:
max=i
return max
num=Numbers()
n=int(input("Enter list of element in list: "))
num.insert_method(n)
print("max is: ",Numbers.find_max(num))
Output:10
Enter list of element in list: 5
Insert element in the list
8
4
2
48
54
max is: 54
11) Write a program that has a class Point with attributes x and y.
#a. Write a method called midpoint that returns a midpoint of a line joining two points.
#b. Write a method called length that returns the length of a line joining two points.
Code:
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def midpoint(self,other):
mid_x=(self.x+other.x)/2
mid_y=(self.y+other.y)/2
mid=(mid_x,mid_y)
print(f"Midpoint of points {(self.x,self.y)} and {(other.x,other.y)} is :-{mid}")
def length(self,other):
dis=((other.x-self.x)**2+(other.y-self.y)**2)**0.5
print(f"Distance Between points {(self.x,self.y)} and {(other.x,other.y)} is : {dis}")
x1=int(input("Enter the value for X1 : "))
y1=int(input("Enter the value for Y1 : "))
x2=int(input("Enter the value for X2 : "))
y2=int(input("Enter the value for Y2 : "))
p=Point(x1,y1)
q=Point(x2,y2)
p.midpoint(q)
p.length(q)
Output:11
Enter the value for X1 : 5
Enter the value for Y1 : 4
Enter the value for X2 : 8
Enter the value for Y2 : 14
Midpoint of points (5, 4) and (8, 14) is :-(6.5, 9.0)
Distance Between points (5, 4) and (8, 14) is : 10.44030650891055
12) Create a class called Complex. Write a menu driven program to read, display, add and subtract two complex
numbers by creating corresponding instance methods.
Code:
class comp:
def __init__(self,re=0,im=0):
self.re=re
self.im=im
def __str__(self):
return "{} {} {}i".format(self.re,"+" if self.im>=0 else "",self.im)
def __add__(self,other):
return comp(self.re+other.re,self.im+other.im)
def __sub__(self,other):
return comp(self.re-other.re,self.im-other.im)
c=comp()
print("__________ENTER FIRST COMPLEX NUMBER__________")
c.r1=int(input("Enter the real part>>>"))
c.i1=int(input("Enter the imag part>>>"))
print("__________ENTER SECOND COMPLEX NUMBER__________")
c.r2=int(input("Enter the real part>>>"))
c.i2=int(input("Enter the imag part>>>"))
z1=comp(c.r1,c.i1)
z2=comp(c.r2,c.i2)
print("""...LIST OF CHOICES...
CHOOSE 1. FOR ADDITION
CHOOSE 2. FOR SUBTRACTION
CHOOSE 3. TO SHOW COMPLEX NUMBER
CHOOSE -1. TO EXIT""")
while True:
a=int(input("Enter the choice>>>"))
if a==1:
print(z1+z2)
elif a==2:
print(z1-z2)
elif a==3:
print("YOUR FIRST COMPLEX NUMBER IS",z1)
print("YOUR SECOND COMPLEX NUMBER IS",z2)
elif a==-1:
print("...THANK YOU FOR USING...")
break
Output:
__________ENTER FIRST COMPLEX NUMBER__________
Code:
class ABC():
def __init__(self,var1,var2):
self.var1=var1
self.var2=var2
def display(self):
print("var1 is : ",self.var1)
print("var2 is : ",self.var2)
def __repr__(self):
return repr(self.var1,self.var2)
obj=ABC(10,20)
obj.display()
print(repr(obj))
print("object.__doc__ : ",obj.__doc__)
print("object.__dict__: ",obj.__dict__)
print("object.__name__: ",ABC.__name__)
print("object.__bases__: ",ABC.__bases__)
Output:13
var1 is : 10
var2 is : 20
14) Create a BankAccount class. Your class should support the following methods:
Code:
class BankAccount:
def __init__(self,account_no=None):
self.account_no=int(input("Enter account no :"))
self.balance = 0
print("New Account Created ")
def deposit(self):
amount = float(input("enter amount to deposit "))
self.balance+=amount
print("New Balance : %f" %self.balance)
def withdraw(self):
amount = float(input("Enter amount to withdraw :"))
if amount > self.balance:
print("insufficient balance")
else:
self.balance-=amount
print("New Balance : %f" %self.balance)
def get_balance(self):
print("Balance : %f" %self.balance)
account=BankAccount()
account.deposit()
account.withdraw()
account.get_balance()
Output:14
Enter account no :10205040
Balance : 199139.000000
#a. hasattr(obj,attr)
#b. getattr(object, attribute_name [, default])
#c. setattr(object, name, value)
#d. delattr(class_name, name)
Code:
class ABC():
def __init__(self,var):
self.var=var
def display(self):
print("var is = ",self.var)
obj=ABC(40)
obj.display()
print("check hasattr :",hasattr(obj,"var"))
getattr(obj,"var")
setattr(obj,"var",40)
print("after set value is :",obj.var)
setattr(obj,"count",40)
print("variable count is :",obj.count)
delattr(obj,"var")
print("after deleting the attribute is :",obj.var)
Output:15
var is = 40
variable count is : 40
16) Write a program to create class Employee. Display the personal information and salary
details of 5 employees using single inheritance.
Code:
class Employee:
def __init__(self):
self.name=input("Enter name ")
self.profile=input("enter profile ")
self.salary=int(input("Enter salary")
class Personal_info(Employee):
def display(self):
print(f"Name:{self.name},Profie:{self.profile},Salary:{self.salary}")
obj=[]
for i in range(5):
print(f"Data of employee{i+1}")
obj.append(Personal_info())
for i in range(5):
obj[i].display()
Output:16
17) WAP that extends the class Employee. Derive two classes Manager and Team Leader from
Employee class. Display all the details of the employee working under a particular Manager and
Team Leader. class Employee:
Code:
def __init__(self,data):
self.data=data
def display_manager(self):
for i in self.data:
if "mm" in i[3]:
print(i)
def display_team_leader(self):
for i in self.data:
if "tl" in i[3]:
print(i)
class Manager(Employee):
def diplay_manager(self):
Employee.display_manager(self)
class TeamLeader(Employee):
def display_team_leader(self):
Employee.display_team_leader(self)
emp=[["vikash",25,"developer","mm123"],["mili",26,"tester","tl123"]]
object_man=Manager(emp)
object_man.diplay_manager()
object_tl=TeamLeader(emp)
object_tl.display_team_leader()
18) Write a program that has a class Point. Define another class Location which has two objects
(Location and destination) of class Point. Also, define a function in Location that prints the
reflection on the y-axis
Code:
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
class location:
def __init__(self,x1,y1,x2,y2):
self.location=Pont(x1,y1)
self.destination=point(x2,y2)
def display(self):
print("location:",self.location.x,self.location.y)
print("destination",self.destination.x,self.destination.y)
def reflection(self):
self.destination.y=-self.destination.y
loc=location(1,2,3,4)
loc.display()
loc.reflection()
print(next(it))
19) WAP that create a class Student having attribute as name and age and Marks class
inheriting Students class with its own attributes marks1, marks2 and marks3 as marks in 3
subjects. Also, define the class Result that inherits the Marks class with its own attribute total.
Every class has its own display() method to display the corresponding details. Use __init__()
and super() to implement the above classes.
Code:
class Student:
def __init__(self):
def display(self):
print("Name:",self.name)
print("age:",self.age)
class Marks(Student):
def __init__(self):
super().__init__()
def display(self):
super().display()
print("mark1: ",self.mark1)
print("mark2: ",self.mark2)
print("mark3: ",self.mark3)
class Result(Marks):
def __init__(self):
super().__init__()
self.total=self.mark1+self.mark2+self.mark3
def display(self):
super().display()
res=Result()
res.display()
Output:19
Enter name: Ratan Tata
Enter age: 74
age: 74
mark1: 45
mark2: 85
mark3: 47
None
20) Write a program that create a class Distance with members km and metres.
#Derive classes School and office which store the distance from your house to school and
office along with other details.
Code:
class Distance:
def __init__(self):
self.km=int(input("Enter distance in kilometer :"))
self.m=int(input("Enter distance in meter :"))
def display(self):
print(f"Distance={self.km}km,{self.m}m")
class School(Distance):
def __init__(self):
super().__init__()
def display(self):
super().display()
class Office(Distance):
def __init__(self):
super().__init__()
def display(self):
super().display()
d=School()
print(d.display())
d=Office()
print(d.display())
21) Write a program to create an abstract class Vehicle. Derive three classes Car,
#Motorcycle and Truck from it. Define appropriate methods and print the details of vehicle.
Code:
from abc import ABC, abstractmethod
class Vahicale(ABC):
@abstractmethod
def Details(self):
pass
class Car(Vahicale):
def Details(self):
print("This is the detail of car ")
print("Racing car")
print("Car has 4 wheels")
class Motorcycle(Vahicale):
def Details(self):
print("detail of motarcycle")
print("Racing bike")
print("two wheelar ")
class Truck(Vahicale):
def Details(self):
print("details of truck")
print("this is havy loded truck")
print("12 wheelar")
c=Car()
c.Details()
m=Motorcycle()
m.Details()
t=Truck()
t.Details()
22) Write a program that has a class Polygon. Derive two classes Rectangle and triangle from
polygon and write methods to get the details of their dimensionsand hence calculate the area.
Code:
class polygon:
def __init__(self,name):
self.name=name
def getdetails(self):
print(f"Eter details of {self.name}")
def area(self):
print(f"area of {self.name}")
class rectangle(polygon):
def getdetails(self):
super().getdetails()
self.l=int(input("Enter length"))
self.b=int(input("Enter breadth"))
def area(self):
super().area()
return self.l*self.b
class triangle(polygon):
def getdetails(self):
super().getdetails()
self.b=int(input("Enter base"))
self.h=int(input("Enter height"))
def area(self):
super().area()
return self.b*self.h
rec=rectangle("rectangle")
rec.getdetails()
print(rec.area())
tri=triangle("triangle")
tri.getdetails()
print(tri.area())
Output:22
Eter details of rectangle
Enter length58
Enter breadth40
area of rectangle
2320
Eter details of triangle
Enter base8
Enter height4
area of triangle
32
23) Write a program that extends the class Shape to calculate the area of a circle and a cone .
(use super to inherit base class methods)
Code:
class Shape:
def __init__(self,r,l=None):
self.r=r
self.l=l
def area(self,name):
print("Area of",name)
class Circle(Shape):
def area(self,name):
super().area(name)
return 3.14*self.r*self.r
class Cone(Shape):
def area(self,name):
super().area(name)
return 3.14*self.r*(self.r+self.l)
circle=Circle(5)
print(circle.area("Circle"))
con=Cone(3,4)
print(con.area("Cone"))
Output:
Area of Circle
78.5
Area of Cone
65.94
24) Write a program to demonstrate hybrid inheritance and show MRO for each class.
Code:
class A:
def __init__(self):
print("class a")
class B(A):
def display(self):
print("class B")
class C:
def display1(self):
print("class c")
class D(C,A):
def display(self):
print("class D")
obj1=A()
obj2=B()
obj3=C()
obj=D()
print(D.mro())
Output:
class a
class a
class a
[<class '__main__.D'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
25) Write a program to overload + operator to multiply to fraction object of fraction class
which contain two instance variable numerator and denominator. Also, define the instance
method simplify() to simplify the fraction objects
Code:
def GCD(num,deno):
rem=num%deno
while rem:
num=deno
deno=rem
rem=num%deno
return deno
class Fraction:
def __init__(self,num=None,deno=None):
self.num=num
self.deno=deno
def __mul__(self,other):
f=Fraction()
f.num=self.num*other.num
f.deno=self.deno*other.deno
f.simplify()
return f
def simplify(self):
gcd=GCD(self.num,self.deno)
self.num//=gcd
self.deno//=gcd
def __str__(self):
return f"{self.num}/{self.deno}"
f1=Fraction(3,4)
print(f1)
f2=Fraction(4,5)
print(f2)
f3=f1+f2
print(f3)
Output:
3/4
4/5
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python39\Python Lab Programs(50).py", line 391, in <module>
f3=f1+f2
TypeError: unsupported operand type(s) for +: 'Fraction' and 'Fraction'
26) Write a program to compare two-person object based on their age by overloading > operator.
Code:
class A:
def __init__(self, age):
self.age = age
def __gt__(self, other):
if(self.age > other.age):
return True
else:
return False
ob1 = A (12)
ob2 = A (13)
if (ob1 > ob2):
print ("ob1 is older than ob2")
else:
print ("ob2 is older than ob1")
Output:
ob2 is older than ob1.
27) Write a program to overload in operator.
Code:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})”. format(self.x,self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
p1 = Point (1, 2)
p2 = Point (2, 3)
print(p1+p2)
Output:
(3,5)
28) WAP to create a Complex class having real and imaginary as it attributes. Overload the +,
-,/,* and += operators for objects of Complex .
Code:
class.
class Complex:
# Defining init method for class
def __init__(self, r, i):
self.real = r
self.img = i
def __str__(self):
return str(self.real)+' + '+str(self.img)+'i'
c1 = Complex (5, 3)
c2 = Complex (2, 4)
print ("sum = ", c1+c2)
print ("Difference = ", c1-c2)
print ("Multiply = ", c1*c2)
print ("Division = ", c1/c2)
print ("Add_and = ", c1.__iadd__(c2))
Output:
sum = (7+7j)
Difference = (3-1j)
Multiply = (10+12j)
Division = (2.5+0.75j)
Add_and = (7+7j)
29) Write a program to inspect the object using type() ,id(), isinstance(), issubclass() and callable() built-
in function.
Code:
x = 5
s = "Python"
y = [1, 2, 3]
print(type(x))
print(type(s))
print(type(y))
Output:
<class 'int'>
<class 'str'>
<class 'list'>
# Python code for isinstance()
class Test:
a = 5
TestInstance = Test()
print (isinstance(TestInstance, Test))
print (isinstance(TestInstance, (list, tuple)))
print (isinstance(TestInstance, (list, tuple,
Test)))
Output:
True
False
True
# Python code for id()
class Foo:
b = 5
dummyFoo = Foo ()
print('id of dummy(Foo) =', id(dummyFoo))
Output:
id of dummy (Foo) = 2047182811392
# Python program to demonstrate
# issubclass()
# Defining Parent class
class Vehicles:
# Constructor
def __init__(vehicleType):
print ('Vehicles is a ', vehicleType)
# Defining Child class
class Car (Vehicles):
# Constructor
def __init__(self):
Vehicles. __init__('Car')
# Driver's code
print (issubclass(Car, Vehicles))
print (issubclass(Car, list))
print (issubclass(Car, Car))
print (issubclass(Car, (list, Vehicles)))
Output:
True
False
True
True
# Python program to illustrate
# callable ()
# a test functions
def Geek ():
return 5
# an object is created of Geek ()
let = Geek
print(callable(let))
# a test variable
num = 5 * 5
print(callable(num))
Output:
True
False
30) WAP to inspect the program code using the functions of inspect module.
Code:
# Import required modules
import inspect
# Create class
class A(object):
pass
# use isclass()
print(inspect.isclass(A))
Output:
True
31.Write a program to create a new list containing the first letters of every element
in an already existing list.
Code:
def firstLetterWord(str):
result = ""
return result
# Driver Code
if __name__ == "__main__":
str = "All the Best"
print(firstLetterWord(str))
Output:
AtB
32. Write a program using reduce() function to calculate the sum of first 10 natural numbers
#Reduce function
from functools import reduce
list2 = [1,2,3,4,5,6,7,8,9,10]
fins = reduce(lambda x,y:x+y, list2)
print(fins)
Output:
55
33. Write a program that convert a list of temperatures in Celsius into Fahrenheit using map()function.
Code:
Celsius = [26.2, 33.2, 29.3, 32.4]
Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius)
print (Fahrenheit)
Output:
# Driver Code
n=5
printSquares(n)
Output:
0 1 4 9 16
35) Write a program that create a custom iterator to create even numbers.
Code:
start = int (input ("Enter the start of range: "))
end = int (input ("Enter the end of range: "))
# Checking condition
if num % 2 == 0:
print (num, end = " ")
Output:
Enter the start of range: 5
Enter the end of range: 10
6 8 10
36.) Write a program to create a generator that starts counting from 0 and raise an exception when counter is equal
to 10.
Code:
def numberGenerator(n):
number = 0
while number < n:
yield number
number += 1
if number==10:
raise OverflowError
myGenerator = numberGenerator(15)
for i in range(12):
print(next(myGenerator))
output:
0
1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
File "D:\ALGOS\competitve\demo.py", line 12, in <module>
print(next(myGenerator))
File "D:\ALGOS\competitve\demo.py", line 7, in numberGenerator
raise OverflowError
OverflowError
37. . Write a program to create a generator to print the Fibonacci number.
Code:
a = int(input('Give amount: '))
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
a = fib()
a.next()
0
for i in range(a):
print a.next()
root.title('Calculator')
disp=Entry(root,width=40,borderwidth=5,bg='#b5a874')
disp.grid(row=0,column=0,columnspan=3,padx=10,pady=10)
def click(num):
global b
b=disp.get()
a=len(disp.get())
h=disp.insert(a,num)
b=disp.get()
def clear():
disp.delete(0,END)
def add():
b=disp.get()
global a
a=int(b)
global operator
operator='+'
disp.delete(0,END)
def mul():
b=disp.get()
global a
a=int(b)
global operator
operator='*'
disp.delete(0,END)
def div():
b=disp.get()
global a
a=int(b)
global operator
operator='//'
disp.delete(0,END)
def equal():
b=disp.get()
global c
c=int(b)
global operated
if operator=='+':
operated=a+c
elif operator=='*':
operated=a*c
elif operator=='//':
operated=a/c
disp.delete(0,END)
disp.insert(0,operated)
btn9=Button(root,padx=40,pady=20,text='9',command=lambda:click(9) ).grid(row=1,column=0)
btn8=Button(root,padx=40,pady=20,text='8',command=lambda:click(8) ).grid(row=1,column=1)
btn7=Button(root,padx=40,pady=20,text='7',command=lambda:click(7) ).grid(row=1,column=2)
btn6=Button(root,padx=40,pady=20,text='6',command=lambda:click(6) ).grid(row=2,column=0)
btn5=Button(root,padx=40,pady=20,text='5',command=lambda:click(5) ).grid(row=2,column=1)
btn4=Button(root,padx=40,pady=20,text='4',command=lambda:click(4) ).grid(row=2,column=2)
btn3=Button(root,padx=40,pady=20,text='3',command=lambda:click(3) ).grid(row=3,column=0)
btn2=Button(root,padx=40,pady=20,text='2',command=lambda:click(2) ).grid(row=3,column=1)
btn1=Button(root,padx=40,pady=20,text='1',command=lambda:click(1) ).grid(row=3,column=2)
btn0=Button(root,padx=40,pady=20,text='0',command=lambda:click(0) ).grid(row=4,column=0)
btn_div=Button(root,padx=40,pady=20,text='/',command=div ,bg='#d9c8a3').grid(row=4,column=1)
btn_clr=Button(root,padx=39,pady=20,text='C',command=clear,bg='#8f0b0b' ).grid(row=4,column=2)
btn_add=Button(root,padx=39,pady=20,text='+',command=add, bg='#d9aca3').grid(row=5,column=0)
btn_mul=Button(root,padx=39,pady=20,text='X',command=mul,bg='#a3d9c9' ).grid(row=5,column=1)
btn_eql=Button(root,padx=39,pady=20,text='=',command=equal,bg='#4a4747' ).grid(row=5,column=2)
root.mainloop()
Output:
39. Write a program to draw colored shapes (line, rectangle, oval) on canvas.
Code:
# Imports each and every method and class
# of module tkinter and tkinter.ttk
from tkinter import * from tkinter.ttk import * class Shape:
def __init__(self, master = None):
self.master = master
def create(self):
# Creates a polygon
self.canvas.create_polygon(points, outline = "blue",
fill = "orange", width = 2)
# Pack the canvas to the main window and make it expandable
self.canvas.pack(fill = BOTH, expand = 1)
if __name__ == "__main__":
Output:
40. Write a program to create a window that disappears automatically after 5 seconds.
Code:
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button
from tkinter.messagebox import _show
mainloop()
Output:
41. Write a program to create a button and a label inside the frame widget. Button should change the color upon
hovering over the button and label should disappear on clicking the button.
Code:
import tkinter as tk
def on_enter(e):
e.widget['background'] = 'green'
def on_leave(e):
e.widget['background'] = 'SystemButtonFace'
root = tk.Tk()
myButton = tk.Button(root,text="Click Me")
myButton.grid()
myButton.bind("<Enter>", on_enter)
myButton.bind("<Leave>", on_leave)
myButton2.bind("<Enter>", on_enter)
myButton2.bind("<Leave>", on_leave)
root.mainloop()
Output:
42. Write a program to create radio-buttons (Male, Female, and Transgender) and a label. Default selection should
be on Female and the label must display the current selection made by user.
Code:
from Tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="male ", variable=var, value=1,
command=sel)
R1.pack( anchor = W )
label = Label(root)
label.pack()
root.mainloop()
Output:
Output:
44. Write a NumPy program to create an array of (3, 4) shape, multiply every element value by 3 and display the new
array.
Code:
import numpy as np
x= np.arange(12).reshape(3, 4)
print("Original array elements:")
print(x)
for a in np.nditer(x, op_flags=['readwrite']):
a[...] = 3 * a
print("New array elements:")
print(x)
output:
Original array elements:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
New array elements:
[[ 0 3 6 9]
[12 15 18 21]
[24 27 30 33]]
45. Write a NumPy program to compute the multiplication of two given matrixes.
Code:
import numpy as np
p = [[1, 0], [0, 1]]
q = [[1, 2], [3, 4]]
print("original matrix:")
print(p)
print(q)
result1 = np.dot(p, q)
print("Result of the said matrix multiplication:")
print(result1)
print(result2)
Output:
original matrix:
[[1, 0], [0, 1]]
[[1, 2], [3, 4]]
Result of the said matrix multiplication:
[[1 2]
[3 4]]
46. Write a Program to create a series from a list, numpy array and dict.
Code:
importpandas as pd
# simple list
lst =['G','E','E','K','S','F',
'O','R','G','E','E','K','S']
# forming series
s =pd.Series(lst)
# output
print(s)
# simple dict
dct = {'G':2,'E':4,'K':2,'S':2,
'F':1,'O':1,'R':1}
# forming series
s = pd.Series(dct)
# output
print(s)
# import pandas as pd
import pandas as pd
# import numpy as np
import numpy as np
# numpy array
arr = np.array(['G','E','E','K','S','F',
'O','R','G','E','E','K','S'])
# forming series
s = pd.Series(arr)
output:
print(s)
Code:
import pandas as pd
import numpy as np
Output:
0 1
0 1 yo
1 4 bro
2 4 low
3 1 NumPy
Code:
import pandas as pd
import numpy as np
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
df = pd.DataFrame({
'ord_no':[70001,np.nan,70002,70004,np.nan,70005,np.nan,70010,70003,70012,np.nan,70013],
'purch_amt':[150.5,270.65,65.26,110.5,948.5,2400.6,5760,1983.43,2480.4,250.45, 75.29,3045.6],
'ord_date': ['2012-10-05','2012-09-10',np.nan,'2012-08-17','2012-09-10','2012-07-27','2012-09-10','2012-10-
10','2012-10-10','2012-06-27','2012-08-17','2012-04-25'],
'customer_id':[3002,3001,3001,3003,3002,3001,3001,3004,3003,3002,3001,3001],
'salesman_id':[5002,5003,5001,np.nan,5002,5001,5001,np.nan,5003,5002,5003,np.nan]})
print("Original Orders DataFrame:")
print(df)
print("\nNumber of missing values of the said dataframe:")
print(df.isna().sum())
Output:
Original Orders DataFrame:
ord_no purch_amt ord_date customer_id salesman_id
0 70001.0 150.50 2012-10-05 3002 5002.0
1 NaN 270.65 2012-09-10 3001 5003.0
2 70002.0 65.26 NaN 3001 5001.0
3 70004.0 110.50 2012-08-17 3003 NaN
4 NaN 948.50 2012-09-10 3002 5002.0
5 70005.0 2400.60 2012-07-27 3001 5001.0
6 NaN 5760.00 2012-09-10 3001 5001.0
7 70010.0 1983.43 2012-10-10 3004 NaN
8 70003.0 2480.40 2012-10-10 3003 5003.0
9 70012.0 250.45 2012-06-27 3002 5002.0
10 NaN 75.29 2012-08-17 3001 5003.0
11 70013.0 3045.60 2012-04-25 3001 NaN
49. Write a program to replace missing values in a column of a dataframe by the mean value of that column.
Code:
import pandas as pd
data = pd.read_csv('item.csv')
# replacing missing values in quantity
# column with mean of that column
data['quantity'] = data['quantity'].fillna(data['quantity'].mean())
50. Write a Pandas program to create a line plot of the opening, closing stock prices of Alphabet Inc. between two
specific dates. Use the alphabet_stock_data.csv file to extract data Write a Pandas program to create a line plot of
the opening, closing stock prices of Alphabet Inc. between two specific dates. Use the alphabet_stock_data.csv file
to extract data.
Code:
Alphabet_stock_data.csv
Date,Open,High,Low,Close,Adj Close,Volume
2020-04-01,1122,1129.689941,1097.449951,1105.619995,1105.619995,2343100
2020-04-02,1098.26001,1126.859985,1096.400024,1120.839966,1120.839966,1964900
2020-04-03,1119.015015,1123.540039,1079.810059,1097.880005,1097.880005,2313400
2020-04-06,1138,1194.660034,1130.939941,1186.920044,1186.920044,2664700
2020-04-07,1221,1225,1182.22998,1186.51001,1186.51001,2387300
2020-04-08,1206.5,1219.069946,1188.160034,1210.280029,1210.280029,1975100
2020-04-09,1224.079956,1225.569946,1196.734985,1211.449951,1211.449951,2175400
2020-04-13,1209.180054,1220.51001,1187.598022,1217.560059,1217.560059,1739800
2020-04-14,1245.089966,1282.069946,1236.930054,1269.22998,1269.22998,2470400
2020-04-15,1245.609985,1280.459961,1240.400024,1262.469971,1262.469971,1671700
2020-04-16,1274.099976,1279,1242.619995,1263.469971,1263.469971,2518100
2020-04-17,1284.849976,1294.430054,1271.22998,1283.25,1283.25,1949000
2020-04-20,1271,1281.599976,1261.369995,1266.609985,1266.609985,1695500
2020-04-21,1247,1254.27002,1209.709961,1216.339966,1216.339966,2153000
2020-04-22,1245.540039,1285.613037,1242,1263.209961,1263.209961,2093100
2020-04-23,1271.550049,1293.310059,1265.670044,1276.310059,1276.310059,1566200
2020-04-24,1261.170044,1280.400024,1249.449951,1279.310059,1279.310059,1640400
2020-04-27,1296,1296.150024,1269,1275.880005,1275.880005,1600600
2020-04-28,1287.930054,1288.050049,1232.199951,1233.670044,1233.670044,2951300
2020-04-29,1341.459961,1359.98999,1325.339966,1341.47998,1341.47998,3793600
2020-04-30,1324.880005,1352.819946,1322.48999,1348.660034,1348.660034,2665400
2020-05-01,1328.5,1352.069946,1311,1320.609985,1320.609985,2072500
2020-05-04,1308.22998,1327.660034,1299,1326.800049,1326.800049,1504000
2020-05-05,1337.920044,1373.939941,1337.459961,1351.109985,1351.109985,1651500
2020-05-06,1361.689941,1371.119995,1347.290039,1347.300049,1347.300049,1215400
2020-05-07,1365.939941,1377.599976,1355.27002,1372.560059,1372.560059,1397600
2020-05-08,1383.130005,1398.76001,1375.47998,1388.369995,1388.369995,1388100
2020-05-11,1378.280029,1416.530029,1377.151978,1403.26001,1403.26001,1410600
2020-05-12,1407.119995,1415,1374.77002,1375.73999,1375.73999,1390600
2020-05-13,1377.050049,1385.482056,1328.400024,1349.329956,1349.329956,1812600
2020-05-14,1335.02002,1357.420044,1323.910034,1356.130005,1356.130005,1603100
2020-05-15,1350,1374.47998,1339,1373.189941,1373.189941,1707700
2020-05-18,1361.75,1392.324951,1354.25,1383.939941,1383.939941,1824000
2020-05-19,1386.996948,1392,1373.484985,1373.484985,1373.484985,1280600
2020-05-20,1389.579956,1410.420044,1387.25,1406.719971,1406.719971,1655400
2020-05-21,1408,1415.48999,1393.449951,1402.800049,1402.800049,1385000
2020-05-22,1396.709961,1412.76001,1391.829956,1410.420044,1410.420044,1309400
2020-05-26,1437.27002,1441,1412.130005,1417.02002,1417.02002,2060600
2020-05-27,1417.25,1421.73999,1391.290039,1417.839966,1417.839966,1685800
2020-05-28,1396.859985,1440.839966,1396,1416.72998,1416.72998,1692200
2020-05-29,1416.939941,1432.569946,1413.349976,1428.920044,1428.920044,1838100
2020-06-01,1418.390015,1437.959961,1418,1431.819946,1431.819946,1217100
2020-06-02,1430.550049,1439.609985,1418.829956,1439.219971,1439.219971,1278100
2020-06-03,1438.300049,1446.552002,1429.776978,1436.380005,1436.380005,1256200
2020-06-04,1430.400024,1438.959961,1404.72998,1412.180054,1412.180054,1484300
2020-06-05,1413.170044,1445.050049,1406,1438.390015,1438.390015,1734900
2020-06-08,1422.339966,1447.98999,1422.339966,1446.609985,1446.609985,1404200
2020-06-09,1445.359985,1468,1443.209961,1456.160034,1456.160034,1409200
2020-06-10,1459.540039,1474.259033,1456.27002,1465.849976,1465.849976,1525200
2020-06-11,1442.47998,1454.474976,1402,1403.839966,1403.839966,1991300
2020-06-12,1428.48999,1437,1386.02002,1413.180054,1413.180054,1944200
2020-06-15,1390.800049,1424.800049,1387.920044,1419.849976,1419.849976,1503900
2020-06-16,1445.219971,1455.02002,1425.900024,1442.719971,1442.719971,1709200
2020-06-17,1447.160034,1460,1431.380005,1451.119995,1451.119995,1548300
2020-06-18,1449.160034,1451.410034,1427.01001,1435.959961,1435.959961,1581900
2020-06-19,1444,1447.800049,1421.349976,1431.719971,1431.719971,3157900
2020-06-22,1429,1452.75,1423.209961,1451.859985,1451.859985,1542400
2020-06-23,1455.640015,1475.94104,1445.23999,1464.410034,1464.410034,1429800
2020-06-24,1461.51001,1475.420044,1429.75,1431.969971,1431.969971,1756000
2020-06-25,1429.900024,1442.900024,1420,1441.329956,1441.329956,1230500
2020-06-26,1431.390015,1433.449951,1351.98999,1359.900024,1359.900024,4267700
2020-06-29,1358.180054,1395.599976,1347.01001,1394.969971,1394.969971,1810200
2020-06-30,1390.439941,1418.650024,1383.959961,1413.609985,1413.609985,2042400
2020-07-01,1411.099976,1443,1409.819946,1438.040039,1438.040039,1775200
2020-07-02,1446.939941,1482.949951,1446.420044,1464.699951,1464.699951,1859100
2020-07-06,1480.060059,1506.589966,1472.859985,1495.699951,1495.699951,1564000
2020-07-07,1490,1516.800049,1483.550049,1485.180054,1485.180054,1458200
2020-07-08,1494.319946,1505.880005,1485.630005,1496,1496,1249700
2020-07-09,1506.449951,1522.719971,1488.084961,1510.98999,1510.98999,1423300
2020-07-10,1506.150024,1543.829956,1496.540039,1541.73999,1541.73999,1856300
2020-07-13,1550,1577.131958,1505.243042,1511.339966,1511.339966,1846400
2020-07-14,1490.310059,1522.949951,1483.5,1520.579956,1520.579956,1585000
2020-07-15,1523.130005,1535.329956,1498,1513.640015,1513.640015,1610700
2020-07-16,1500,1518.689941,1486.310059,1518,1518,1519300
2020-07-17,1521.619995,1523.439941,1498.420044,1515.550049,1515.550049,1456700
2020-07-20,1515.26001,1570.290039,1503.599976,1565.719971,1565.719971,1557300
2020-07-21,1586.98999,1586.98999,1554.280029,1558.420044,1558.420044,1218600
2020-07-22,1560.5,1570,1546.099976,1568.48999,1568.48999,932000
2020-07-23,1566.969971,1571.869995,1507.391968,1515.680054,1515.680054,1627600
2020-07-24,1498.930054,1517.635986,1488.400024,1511.869995,1511.869995,1544000
2020-07-27,1515.599976,1540.969971,1515.209961,1530.199951,1530.199951,1246000
2020-07-28,1525.180054,1526.47998,1497.660034,1500.339966,1500.339966,1702200
2020-07-29,1506.319946,1531.251953,1501.329956,1522.02002,1522.02002,1106500
2020-07-30,1497,1537.869995,1492.219971,1531.449951,1531.449951,1671400
2020-07-31,1505.01001,1508.949951,1454.030029,1482.959961,1482.959961,3439900
2020-08-03,1486.640015,1490.469971,1465.640015,1474.449951,1474.449951,2330200
2020-08-04,1476.569946,1485.560059,1458.650024,1464.969971,1464.969971,1903500
2020-08-05,1469.300049,1482.410034,1463.459961,1473.609985,1473.609985,1979500
2020-08-06,1471.75,1502.390015,1466,1500.099976,1500.099976,1995400
2020-08-07,1500,1516.844971,1481.640015,1494.48999,1494.48999,1576600
2020-08-10,1487.180054,1504.074951,1473.079956,1496.099976,1496.099976,1289300
2020-08-11,1492.439941,1510,1478,1480.319946,1480.319946,1454400
2020-08-12,1485.579956,1512.385986,1485.25,1506.619995,1506.619995,1437700
2020-08-13,1510.339966,1537.25,1508.005005,1518.449951,1518.449951,1455200
2020-08-14,1515.660034,1521.900024,1502.880005,1507.72998,1507.72998,1354800
2020-08-17,1514.670044,1525.609985,1507.969971,1517.97998,1517.97998,1378300
2020-08-18,1526.180054,1562.469971,1523.709961,1558.599976,1558.599976,2027100
2020-08-19,1553.310059,1573.680054,1543.949951,1547.530029,1547.530029,1660600
2020-08-20,1543.449951,1585.869995,1538.199951,1581.75,1581.75,1706900
2020-08-21,1577.030029,1597.719971,1568.005005,1580.420044,1580.420044,1446500
2020-08-24,1593.97998,1614.170044,1580.569946,1588.199951,1588.199951,1409900
2020-08-25,1582.069946,1611.619995,1582.069946,1608.219971,1608.219971,2247100
2020-08-26,1608,1659.219971,1603.599976,1652.380005,1652.380005,3993400
2020-08-27,1653.680054,1655,1625.75,1634.329956,1634.329956,1861600
2020-08-28,1633.48999,1647.170044,1630.75,1644.410034,1644.410034,1499800
2020-08-31,1647.890015,1647.964966,1630.310059,1634.180054,1634.180054,1823400
2020-09-01,1636.630005,1665.72998,1632.219971,1660.709961,1660.709961,1826700
2020-09-02,1673.775024,1733.180054,1666.329956,1728.280029,1728.280029,2511200
2020-09-03,1709.713989,1709.713989,1615.060059,1641.839966,1641.839966,3107800
2020-09-04,1624.26001,1645.109985,1547.613037,1591.040039,1591.040039,2608600
2020-09-08,1533.51001,1563.86499,1528.01001,1532.390015,1532.390015,2610900
2020-09-09,1557.530029,1569,1536.051025,1556.959961,1556.959961,1774700
2020-09-10,1560.640015,1584.081055,1525.805054,1532.02002,1532.02002,1618600
2020-09-11,1536,1575.199951,1497.359985,1520.719971,1520.719971,1597100
2020-09-14,1539.005005,1564,1515.73999,1519.280029,1519.280029,1696600
2020-09-15,1536,1559.569946,1531.834961,1541.439941,1541.439941,1331100
2020-09-16,1555.540039,1562,1519.819946,1520.900024,1520.900024,1311700
2020-09-17,1496,1508.297974,1470,1495.530029,1495.530029,1879800
2020-09-18,1498.01001,1503.003052,1437.130005,1459.98999,1459.98999,3103900
2020-09-21,1440.060059,1448.359985,1406.550049,1431.160034,1431.160034,2888800
2020-09-22,1450.089966,1469.52002,1434.530029,1465.459961,1465.459961,1583200
2020-09-23,1458.780029,1460.959961,1407.699951,1415.209961,1415.209961,1657400
2020-09-24,1411.030029,1443.708984,1409.849976,1428.290039,1428.290039,1450200
2020-09-25,1432.630005,1450,1413.339966,1444.959961,1444.959961,1323000
2020-09-28,1474.209961,1476.800049,1449.301025,1464.52002,1464.52002,2007900
2020-09-29,1470.390015,1476.662964,1458.805054,1469.329956,1469.329956,978200
2020-09-30,1466.800049,1489.75,1459.880005,1469.599976,1469.599976,1700600
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-09-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df2 = df.loc[new_df]
plt.figure(figsize=(10,10))
df2.plot(x='Date', y=['Open', 'Close']);
plt.suptitle('Opening/Closing stock prices of Alphabet Inc.,\n 01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.xlabel("Date",fontsize=12, color='black')
plt.ylabel("$ price", fontsize=12, color='black')
plt.show()
Output:
===============================================END=============================================