BCA SEM 5 Python Important Programs For Practical
Python SEM - 5
1) Write a program to swap two numbers without taking a temporary variable.ANS:
a = 10
b = 20
print("value of a is = " + a +"value of b = " + b)
a, b = b, a
print("Updated value of a is = " + a + "Updated value of b = " + b)
2) Write a program to create a Student class with name, age and marks as data members. Also create a method named display() to view the student details. Create an object to Student class and call the method using the object.
ANS:
ANS:
class Student:
def __init__(self):
self.name = "Ramesh"
self.age = 20
self.marks= 90
def display (self):
print("Hello " + self.name)
print("Age : " , self.age)
print("Marks : ", self.marks)
s1 = Student()
s1.display()
ANS:
from array import*
a = array("i",[1,2,3,4,2,5,2,6,7,8])
print("Element in Array a is ",a)
a.append(10)
print("After append method :")
a.insert(4,9)
print("After Insert method : ",a)
a.remove(9)
print("After Remove method :",a)
a.pop()
print("after pop method ",a)
print("Index of element 6 is : ", a.index(6))
print("Total occurrence of 2 : " , a.count(2))
b = a.tolist()
print ("Type of B is :", type(b))
print("Element of b is :",b)
4) Write a program to handle some built in exceptions like ZeroDivisionError.
ANS :
try:
a=int(input("Enter value of a = "))
b =int(input("Enter value of b = "))
c = a/b
print("Division of a and b is :",c)
except ZeroDivisionError:
print("ZeroDivsionError Occurred")
5) Write a program to find out and display the common and the non-common elements in the list using membership operators
ANS)
list1=[1,2,3,4,5,4,3,6,7,8]
common=[]
nonCommon=[]
for i in list1:
if(list1.count(i)>1):
common.append(i)
else:
nonCommon.append(i)
print("Common Elements in the list are: ",set(common))
print("Non Common Elements in the list are:",nonCommon)
6) Write a program to create Student class with a constructor having more than one parameter.
def __init__(self,sname='',sage=0,smarks=0):
self.name = sname
self.age = sage
self.marks= smarks
def display (self):
print("-----------------")
print("Hello " + self.name)
print("Age : " , self.age)
print("Marks : ", self.marks)
sname = input("Enter Your Name : ")
sage = int(input("Enter Your Age : "))
smarks = int(input("Enter Your Marks : "))
s1 = Student()
s1.display()
s2 = Student(sname,sage,smarks)
s2.display()
7) Write a python program that removes any repeated items from a list so that each item appears at most once. For instance, the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0].
print("Age : " , self.age)
print("Marks : ", self.marks)
sname = input("Enter Your Name : ")
sage = int(input("Enter Your Age : "))
smarks = int(input("Enter Your Marks : "))
s1 = Student()
s1.display()
s2 = Student(sname,sage,smarks)
s2.display()
7) Write a python program that removes any repeated items from a list so that each item appears at most once. For instance, the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0].
ANS:
lst = []
n = int(input("How many number u want:"))
for i in range(n):
lst.append(int(input("Enter elements:")))
print("List : ",lst)
lst2 = set(lst)
lst2 = list(lst2) # this line convert set # into list if needed
print("List with unique values : ",lst2)
8) Write a program to import “os” module and to the current working directory and returns a list of all module functions
ANS:
import os print("\nCurrent Working Directory is :",os.getcwd())
print("\nMethods of OS Modules are :\n", dir(os))
9) Write a program that evaluates an expression given by the user at run time using eval() function. Example: Enter and expression: 10+8-9*2-(10*2) Result: -20
14) Create a sample list of 7 elements and implement the List methods mentioned: append, insert, copy, extend, count, remove, pop, sort, reverse and clear.
18) Write a program to convert the elements of two lists into key-value pairs of a dictionary
value = [1,2,3]
d = dict(zip(keys , value))
print(d)
9) Write a program that evaluates an expression given by the user at run time using eval() function. Example: Enter and expression: 10+8-9*2-(10*2) Result: -20
ANS:
a = input("Enter Math Function to Evaluate:")
b = eval(a)
print ("The result of you Enter Maths function is :",b)
10) Write a program to implement single inheritance in which two sub classes are derived from a single base class.
ANS)
class Bank(object):
class Bank(object):
cash=5000000
@classmethod
def available_cash(cls):
print(cls.cash)
class AndraBank(Bank):
pass
class StateBank(Bank):
cash=2000000
@classmethod
def available_cash(cls):
print(cls.cash+Bank.cash)
a=AndraBank()
a.available_cash()
s=StateBank()
s.available_cash()
11) Write a lambda/Anonymous function to find bigger number in two given numbers.
ANS:
ANS:
c=lambda x,y : x if x>y else y
a,b=[int(i) for i in input("Enter two numbers:").split()]
print(c(a,b),"is biggest")
12) Write a python program that asks the user to enter a length in centimeters. If the user enters a negative length, the program should tell the user that the entry is invalid. Otherwise, the program should convert the length to inches and print out the result. (2.54 = 1 inch).
ANS:
ANS:
cm = int(input("Enter length in cm : "))
if cm < 0:
print("invalid entry")
else:
print(cm/2.54, "inches")
13) Write a program to understand the order of execution of methods in several base classes according to method resolution order (MRO).
ANS:
class A(object):
def method(self
print('A class method')
super().method()
class B(object):
def method(self):
print('B class method')
super().method()
class C(object):
def method(self):
print('C class method')
class X(A, B):
def method(self):
print('X class method')
super().method()
class Y(B, C):
def method(self):
print('Y class method')
super().method()
class P(X, Y, C):
def method(self):
print('P class method')
super().method()
p=P()
p.method()
print(p.mro())
14) Create a sample list of 7 elements and implement the List methods mentioned: append, insert, copy, extend, count, remove, pop, sort, reverse and clear.
ANS:
lst=[1,2,3,4,5,6,7]
print("Element in list are:",lst)
lst.insert(7,8)
print("Element in list after insert are:",lst)
lst1=lst.copy()
print("Element in new list after coping are:",lst1)
lst.extend(lst1)
print("Elements in list after extend",lst)
print("1 occures in list",lst.count(1),"times")
lst.remove(5)
print("After removing element:",lst)
print("Removing last element",lst.pop())
lst.sort()
print("After sorting list :",lst)
lst.reverse()
print("After reversing:",lst)
lst.clear()
print("After cleat method list:",lst)
15) Write a program to handle multiple exceptions like SyntaxError and TypeError
ANS:
ANS:
try:
date=eval(input("Enter Date:"))
print(date)
a=[1,2,3,4,5,6]
b=[]
c=a/b
print(c)
except TypeError:
print("Cannot Divide by empty list")
except SyntaxError:
print("Invalid Date")
16) Write a program to search an element in the list using for loop and also demonstrate the use of “else” suite with for loop.
ANS:
lst=[1,2,3,4,5,6,7,8]
print(lst)
val=int(input("Enter element to search:"))
flag=0
for i in lst:
if i == val:
print("Position:",lst.index(i))
flag=1
break
if(flag==1):
print("Element found")
else:
print("Element not found")
17) Write a program to create a static method that counts the number of instances created for a class.
ANS:
class Myclass:
n=0
def __init__(self):
Myclass.n+=1
@staticmethod
def noObjects():
print('No. of instances created: ', Myclass.n)
obj1=Myclass()
obj2=Myclass()
obj3=Myclass()
Myclass.noObjects()
18) Write a program to convert the elements of two lists into key-value pairs of a dictionary
ANS:
keys = ["Hey","Hello","Hii"]value = [1,2,3]
d = dict(zip(keys , value))
print(d)
Comments
Post a Comment