Python
Python
")
start = int(input("Enter Number : ")) else:
1.Write a program to swap two numbers without taking a temporary
end = int(input("Enter Number : ")) print("Not Same")
variable.
for num in range(start, end + 1): b = 30
a = int(input("Enter Value Of First Variable"))
if num%2 == 0: if(a is b):
b = int(input("Enter Value Of Second Variable"))
print(num, end = " ") print("same")
a=a+b
7. Write a Python program to print all odd numbers in a range else:
b=a-b
for num in range(start, end + 1): print("Not Same")
a=a-b
if num%2 != 0: if(a is not b):
print("A is :",a," B is :",b)
print(num, end = " ") print("Not Same")
2. Write a Python program to check if element exists in list
8. Write a Python Program to Reversing a List else:
list = [5,8,9,4,5,7,6]
lst = [10,11,12,13,14,15] print("Same")
i = int(input("Enter Number To Check Value In List :"))
l = [] 14.Write a Python program to find sum of elements in list
if(i in list):
for i in lst: list1 = [10,5,2,11,13]
print("Exist")
l.insert(0,i) total = 0
else:
print(l) for i in range(0, len(list1)):
print("Not")
9. Write a Python program to find sum of elements in list total = total + list1[i]
3. Write a Python program to find largest number in a list
list1 = [10,5,2,11,13] print("The total number is : ",total)
list1 = [50,80,60,20,450,10]
total = 0 15.Write a python program to find the sum of even numbers using
#list1.sort()
for i in range(0, len(list1)): command line arguments.
#print("The Smallest Number Is :",list1[0])
total = total + list1[i] import sys
#print("The Largest Number Is :",list1[-1])
print("The total number is : ",total) print("Enter two number : ")
#print("The largest number is :",max(list1))
10.Write a Python Program to Multiply all numbers in the list x = int(sys.argv[1])
def maxi(list1):
def multi(mylist): y = int(sys.argv[2])
max = list1[0]
result = 1 total = x+y
for x in list1:
for x in mylist: print(total)
if x > max:
result = result * x '''
max = x
return result 16.Write a program to search an element in the list
return max
list1 = [2,4,7] mylist = [];
print("largest number is :",maxi(list1))
list2 = [1,2,3] print("Enter Five Elements")
4. Write a Python program to find second largest number in a list
print(multi(list1)) for i in range(5):
list1 = [50,80,60,20,450,10]
print(multi(list2)) a = int(input("Enter Number : "))
def secondnum(list1):
11.Create a sequence of numbers using range datatype to display 1 to 30, mylist.append(a)
snum = 0
with an increment of 2 print("Enter Elements Who Wants To Search : ")
larg = min(list1)
for i in range(0,30,2): ele = int(input())
for i in range(len(list1)):
print(i, end = " ") for i in range(5):
if list1[i] > larg:
print() if ele == mylist[i]:
snum = larg
12.Write a Python program to find out and display the common and the print("\nElement found at Index:", i)
larg = list1[i]
non-common elements in the list using print("Element found at Position:", i+1)
else:
membership operators 17.Write a program to create one array from another array.
snum = max(snum, list1[i])
list1 = [1,2,8,4,6] arr1 = [1,5,2,4,0];
return snum
list2 = [6,7,8,1] arr2 = [None] * len(arr1)
print(secondnum(list1))
for item in list1: for i in range(0, len(arr1)):
5. Write a Python program to find N largest elements from a list
if item in list2: arr2[i] = arr1[i]
list1 = [2,6,8,4,10,1]
print(item,"Overlapping") print("Element of original array : ")
n=2
else: for i in range(0, len(arr1)):
def nlarge(list1, n):
print(item,"Not Overlapping") print(arr1[i])
final_list = []
13.Create a program to display memory locations of two variables using print("Element of new array : ")
for i in range(0,n):
id() function, and then use identity for i in range(0, len(arr2)):
maxl = 0
operators two compare whether two objects are same or not. print(arr2[i])
for j in range(len(list1)):
a=20 18.Write a Python program to find the frequency of each element in the
if list1[j] > maxl:
b=20 array
maxl = list1[j];
if(id(a) == id(b)): arr = [1,1,1,2,2,2,2,3,3,3,3]
list1.remove(maxl)
print("Same") count = {}
final_list.append(maxl)
else: for e in arr:
print(final_list)
print("Not Same") if e in count:
nlarge(list1,n)
if(id(a)==id(b)): count[e] += 1
else: } print("The original string is: ",str)
count[e] = 1 print("choose any cricketer name in this list:",Dictionary.keys()) print("The reverse string is",reverse_string(str)) # Function call
for key,value in count.items(): search=input() 30.Write a Python Program to generate a Random String..
print(f"{key}: {value}") print(Dictionary.get(search)) import string
19.Write a Python program to sort the elements of an array in ascending 24.Write a program to convert the elements of two lists into key-value import random # define the random module
order pairs of a dictionary. S = 10 # number of characters in the string.
arr = [5,2,8,7,1] test_keys = ["Rash", "Kil", "Varsha"] # call random.choices() string module to find the string in Uppercase +
temp = 0 test_values = [1, 4, 5] numeric data.
print("Element of orginals array : ") print ("Original key list is : " + str(test_keys)) ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k = S))
for i in range(0, len(arr)): print ("Original value list is : " + str(test_values)) print("The randomly generated string is : " + str(ran)) # print the random
print(arr[i], end=" ") res = {} data
for i in range(0, len(arr)): for key in test_keys:
for j in range(i+1, len(arr)): for value in test_values:
ASSIGNMENT -3
if(arr[i]>arr[j]): res[key] = value 1. Write a program to create a Student class with name, age and marks as
temp = arr[i] test_values.remove(value) datamembers. Also create a method named display() to view the student
arr[i] = arr[j] break details.Create an object to Student class and call the method using the
arr[j] = temp print ("Resultant dictionary is : " + str(res)) object class student:
print() 25.Write a Python Program to reverse a string def __init__(self): #constructor to initialize the variables
print("Element of array sorted in ascending order : ") def reverse_string(str): self.name='Vishnu'
for i in range(0, len(arr)): str1 = "" # Declaring empty string to store the reversed string self.age=20
print(arr[i], end="") for i in str: self.marks=1050 #self represents the current object
20.Write a python program that removes any repeated items from a list so str1 = i + str1 def display(self):
that each item appears at most once return str1 # It will return the reverse string to the caller function print('Name ',self.name)
test_list = [1, 3, 5, 6, 3, 5, 6, 1] str = "JavaTpoint" # Given String print('Name ',self.age)
print ("The original list is : " + str(test_list)) print("The original string is: ",str) print('Name ',self.marks)
res = [] print("The reverse string is : ",reverse_string(str)) s1=student()
[res.append(x) for x in test_list if x not in res] 26.Write a Python Program to Sort Words in Alphabetic Order s2=student()
print ("The list after removing duplicates : "+ str(res)) my_str = "Hello this Is an Example With cased letters" s1.display()
21.Write a program to create a list using range functions and perform words = [word.lower() for word in my_str.split()] s2.display()
append, update and delete elements operations in it words.sort() 2. Write a program to create Student class with a constructor having more
list1=[i for i in range(0,9)] print("The sorted words are:") than one parameter.
print(list1) for word in words: class student:
list1.append(12) print(word) def __init__(self,name='Mark',age=30,marks=100):#default parameters
print(list1) 27.Write a Python Program to Remove Punctuation from a String self.name=name
list1.insert(1,15) punctuations = (3comment)!()-[]{};:'"\,<>./?@#$%^&*_~(3comment) self.age=age
print(list1) my_str = "Hello!!!, he said ---and went." self.marks=marks
list1.remove(7) no_punct = "" def display(self):
print(list1) for char in my_str: print('Name ',self.name)
22.Write a program to accept elements in the form of a tuple and display if char not in punctuations: print('Name ',self.age)
its minimum, maximum, sum and average. no_punct = no_punct + char print('Name ',self.marks)
t=tuple() print(no_punct) s1=student('John',45,90)
n=int(input("Total number of values in tuple")) 28.Write a Python Program to sort a dictionary s2=student()
for i in range(n): color_dict = {'red':'#FF0000', s1.display()
a=input("enter elements") 'green':'#008000', s2.display()
t=t+(a,) 'black':'#000000', 3. Write a program to demonstrate the use of instance and class/static
print ("maximum value=",max(t)) 'white':'#FFFFFF'} variables.
print ("minimum value=",min(t)) for key in sorted(color_dict): class sample:
23.Create a dictionary that will accept cricket players name and scores in a print("%s: %s" % (key, color_dict[key])) y=20 # It is a class variable
match. Display runs by entering the player’s name. 29.Write a Python Program to reverse a string def __init__(self):
print("Welcome to Dictionary.") def reverse_string(str): self.x=10
Dictionary={ str1 = "" # Declaring empty string to store the reversed string def modify(self):
"m s dhoni":"51", for i in str: self.x=self.x+1
"virat kohali": "37", str1 = i + str1 @classmethod
"rishabh panth": "23", return str1 # It will return the reverse string to the caller function def edit(cls):
"hardik pandya": "98", cls.y=cls.y+5
"harshal patel": "23", s1=sample()
str = "JavaTpoint" # Given String s2=sample()
"k l rahul": "25"
print('x in s1=',s1.x) 7. Create a Bank class with two variables name and balance. Implement a Save the program by student.py. Create another program to use the
print('x in s2=',s2.x) constructor to initialize the variables. Also implement deposit and Student
s1.modify() withdrawals class which is already available in student.py. from student import student
print('x in s1=',s1.x) using instance methods. s=student()
print('x in s2=',s2.x) import sys s.setid(100)
s3=sample() class bank: s.setname('Rakesh')
s4=sample() def __init__(self,name,balance=0.0): s.setmarks(970)
s3.edit() self.name=name print('id=',s.getid())
#s4.edit() self.balance=balance print('name=',s.getname())
print('x in s3=',s1.y) def deposit(self,amt): print('marks=',s.getmarks())
print('x in s4=',s2.y) self.balance=self.balance+amt 10. Write a program to access the base class constructor from a sub class
4. Write a program to store data into instances using mutator methods return self.balance by using
and to retrieve data from the instances using accessor methods. def withdraw(self,amt): super() method and also without using super() method.
class student: if (amt>self.balance): class father:
def setname(self,name): print('Balance amount is less, so no withdrawal') def __init__(self):
self.name=name else: self.property=80000
def setmarks(self,marks): self.balance=self.balance-amt print('Constructor is called')
self.marks=marks return self.balance def display(self):
def getname(self): name=input('Enter Name:') print('Father\'s property = ',self.property)
return(self.name) b=bank(name) class son(father):
def getmarks(self): while(True): pass
return(self.marks) print('d-deposit, w-withdraw, e-Exit') s=son()
n=int(input('How many students?')) choice=input('Your choice ') s.display()
i=0 if choice=='e' or choice=='E': #display() method of father class will be called. It will be inherited.
while(i<n): sys.exit() #declare a constructor in the base class
s=student() amt=float(input('Enter amount')) #Q-10.2
name=input('Enter name --> ') if choice=='d' or choice=='D': class father:
s.setname(name) print('Amount after deposit = ',b.deposit(amt)) def __init__(self,property=0.0):
marks=int(input('Enter marks --> ')) elif choice=='w' or choice=='W': self.property=property
s.setmarks(marks) print('Amount after withdrawl =',b.withdraw(amt)) def display(self):
print('Name ',s.getname()) 8. Write a program to create a Emp class and make all the members of the print('Father\s property = ',self.property)
print('Marks ',s.getmarks()) Emp class son(father):
i=i+1 class available to another class (Myclass). [By passing members of one def __init__(self,property1=0,property=0):
print('_________________') class to super().__init__(property)
5. Write a program to use class method to handle the common features of another] self.property1=property1
all the class emp: def display(self):
instance of Student class. def __init__(self,id,name,salary): print('Child\'s property = ',self.property1+self.property)
class bird: self.id=id s=son(2000,80000)
wings=2 #static or class variable self.name=name s.display()
@classmethod self.salary=salary 11. Write a program to override super class constructor and method in sub
def fly(cls,name): def display(self): class.
print('{} flies with {} wings'.format(name,cls.wings)) print('id= ',self.id) class A:
bird.fly('sparrow') print('name= ',self.name) def __init__(self,x=5,y=5):
bird.fly('pigeon') print('salary= ',self.salary) self.x=x
6. Write a program to create a static method that counts the number of class myclass: self.y=y
instances created for a class. @staticmethod def display(self):
class trial: def mymethod(e): print('x= ',self.x)
count=0 e.salary+=10000 print('y= ',self.y)
def __init__(self): e.display() class B(A):
trial.count+=1 e=emp(10,'Raj',40000) def __init__(self,x,y,z=5):
@staticmethod e.display() super().__init__(x,y)
def countinst(): print('___________________') self.z=z
print('count=',trial.count) myclass.mymethod(e) def display(self):
t1=trial() 9. Create a Student class to with the methods set_id, get_id, set_name, super().display()
t2=trial() get_name, set_marks and get_marks where the method name starting print('z= ',self.z)
t=trial() with set are used to assign the values and method name starting with get b1=B(7,7,7)
trial.countinst() are returning the values. b2=B(10,10)
b1.display() def method(self): return self.pages+other.pages
print('b2 is ') print('B class method') class booky:
b2.display() super().method() def __init__(self,pages):
12. Write a program to implement single inheritance in which two sub class C(object): self.pages=pages
classes are def method(self): b1=bookx(100)
derived from a single base class. print('C class method') b2=booky(150)
class A: super().method() print('Total pages = ',b1+b2)
def __init__(self,x=5,y=5): class X(A,B): 17. Write a program to show method overloading to find sum of two or
self.x=x def method(self): three
self.y=y print('X class method') numbers.
def display(self): super().method() class myclass:
print('x= ',self.x) class Y(B,C): def sum(self,a=None,b=None,c=None):
print('y= ',self.y) def method(self): if a!=None and b!=None and c!=None:
class B(A): print('Y class method') print('a+b+c=',a+b+c)
def __init__(self,x,y,z=5): super().method() elif a!=None and b!=None:
super().__init__(x,y) class P(X,Y,C): print('a+b=',a+b)
self.z=z def method(self): else:
def display(self): print('P class method') print('please enter 2 or 3 arguments')
super().display() super().method() m=myclass()
print('z= ',self.z) p=P() m.sum(3,4,5)
class C(A): p.method() m.sum(5.5,3.5)
def __init__(self,x,y,p=25): #print('--------------') m.sum(10)
super().__init__(x,y) #print(p.mro()) 18. Write a program to override the super class method in subclass.
self.p=p 15. Write a program to check the object type to know whether the import math
def display(self): method exists in class square:
super().display() the object or not. def area(self,x):
print('z= ',self.p) class dog: print('Square area = ',x*x)
b1=B(7,7,7) def bark(self): class circle(square):
b2=B(10,10) print('Bow wow!') def area(self,x):
c1=C(2,2) class duck: print('Circle area = ',math.pi*x*x)
b1.display() def talk(self): c=circle()
print('b2 is ') print('Quack Quack!') c.area(15)
b2.display() class human:
print('c2 is ') def talk(self):
#ASSIGNMENT-4
c1.display() print('Hello Hi') 1. Write a program to handle some built in exceptions like
13. Write a program to implement multiple inheritance using two base def call_talk(obj): ZeroDivisionError, NameError
classes. if hasattr(obj,'talk'): no1=int(input("Enter the first number"))
class father: obj.talk() no2=int(input("Enter the second number"))
def height(self): elif hasattr(obj,'bark'): try:
print('Height is 6 feet') obj.bark() ans=no1/no2
class mother: else: except ZeroDivisionError:
def color(self): print('wrong object passed') print("this is zero division error")
print('Color is brown') x=duck() else:
class child(father,mother): call_talk(x) print("Answer is",ans)no1=int(input("Enter the first number"))
pass x=human() no2=int(input("Enter the second number"))
c=child() call_talk(x) try:
print('child\'s inherited qualities') x=dog() ans=no1/no2
c.height() call_talk(x) except ZeroDivisionError:
c.color() 16 Write a program to overload the addition operator (+) to make it act on print("this is zero division error")
14. Write a program to understand the order of execution of methods in the class else:
several base objects. print("Answer is",ans)
classes according to method resolution order (MRO). class bookx: 2. Write a program to handle multiple exceptions like SyntaxError and
class A(object): def __init__(self,pages): TypeError
def method(self): self.pages=pages try:
print('A class method') def __add__(self,other):#overloading + operator self is for b1 and other is no1=eval(input("Enter the first number"))
super().method() for b2 no2=eval(input("Enter the second number"))
class B(object): print('self pages ',self.pages,' other pages ',other.pages) ans=no1/no2
except(TypeError,SyntaxError): except error as e: except error as e:
print("Error can occour") print(e) print(e)
else: Q7 Write a program to retrieve and display all the rows in the employee 9. Write a program to delete a row from an employee table by accepting
print("Answer is",ans) table. the
3. Write a program to import “os” module and to print the current [First create an employee table in the Sample_DB employee identity number (eid) from the user.
working with the fields as eid, name, sal . Also enter some valid records] import mysql.connector
directory and returns a list of all module functions import mysql.connector try:
import os try: mydb=mysql.connector.connect(host="localhost",user="root",password="",
#return the absolute path mydb=mysql.connector.connect(host="localhost",user="root",password="", database="my_db")
print(os.getcwd) database="my_db") print(mydb)
#return the list of function of os print(mydb) if(mydb):
print(dir(os)) if(mydb): print("database connected")
4. Write a program to provide a function for making file lists from print("database connected") else:
directory wildcard searches. else: print("database not conected")
import os print("database not conected") cur =mydb.cursor()
def FindFile(filename,searchpath): cur = mydb.cursor() empid =input("Enter Employee id ")
result=[] cur.execute("create table emp1(id varchar(10)primary key,name sql=("delete from emp1 where id =%s")
for root,dir,files in os.walk(searchpath): varchar(10),sal numeric(15))") val = (empid)
if filename in files: print("Employee table created") cur.execute(sql,val)
result.append(os.path.join(root,filename)) print("insert data") print("Record Deleted")
if result == []: cur.execute("insert into emp1 values('id001','Raj','150')") mydb.commit()
return("Not found") cur.execute("insert into emp1 values('id002','Raju','10')") cur.execute("select * from emp1")
else: cur.execute("insert into emp1 values('id003','Ram','12')") rows=cur.fetchall()
return result cur.execute("select *from emp1") for i in rows:
name=input("Enter file name with extention for file cretor :") row =cur.fetchall() print(i)
f=open(name,'w') for i in row: except error as e:
f.close() print(i) print(e)
file=input("Enter file name for searching : ") mydb.commit() 10. Write a program to increase the salary (sal) of an employee in the
print(FindFile(file,os.getcwd())) except error as e: employee table by accepting the employee identity number (eid) from the
5. Write a program to import datetime module and format the date as print(e) user.
required. Also use the same module to calculate the difference between 8. Write a program to insert several rows into employee table from the import mysql.connector
your birthday and today in days. keyboard. try:
import datetime import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passw
year=int(input("Enter the year of your birth" )) try: ord="",database="My_Db")
month=int(input("Enter the month of your birth")) mydb=mysql.connector.connect(host="localhost",user="root",password="", print(mydb)
day=int(input("Enter the day of your bith ")) database="my_db") if(mydb):
birthday=datetime.datetime.now() print(mydb) print("database connected")
Difference=now-birthday if(mydb): else:
print("Difference is ",Difference.days,"days") print("database connected") print("database not conected")
6. Write a program to create a database named “Sample_DB” in MySQL(). else: cur =mydb.cursor()
[First ensure connection is made or not and then check if the database print("database not connected") empid =input("Enter Employee id ")
Sample_DB already exists or not, if yes then print appropriate message] cur=mydb.cursor() increment=int(input("Enter Increment Amount"))
import mysql.connector while("True"): sql="update employee set sal=sal+%s where eid=%s"
mydb=mysql.connector.connect(host="localhost",user="root",password="") choice=input("Would you like to insert new record") val=(increment,empid,)
print(mydb) if(choice=="Yes" or choice=="yes"): cur.execute(sql,val)
if(mydb): empid=input("Enter Employee id") print("Recrd update")
print("database connected") name=input("Enter Employee name") mydb.commit()
else: salary=int(input("Enter employee salary")) cur.execute("select * from employee")
print("database not conected") sql="insert into emp1(id,name,sal)values(%s,%s,%s)" rows=cur.fetchall()
try: val=(empid,name,salary) for i in rows:
cur = mydb.cursor() cur.execute(sql,val) print(i)
cur.execute("Create database My_employee") mydb.commit() except error as e:
cur.execute("show databases") print("record inserted") print(e)
my=cur.fetchall() elif(choice=="No" or choice=="no"): 11. Write a program to create a table named new_employee_tbl with the
print("database create") break fields eno , ename , gender and salary in Sample_DB database. The
for i in my: else: datatypes of the fields are eno-int, ename-char(30), gender-char(1) and
print(i) print("Plz.. enter valid input") salary-float.
import mysql.connector
try:
mydb=mysql.connector.connect(host="localhost",user="root",password="",
database="my_db")
print(mydb)
if(mydb):
print("database connected")
else:
print("database not connected")
cur=mydb.cursor()
cur.execute("create table new_employee_tbl1(eno int,ename
char(30),gender char(1),salary
float)")
print("table Created")
except error as e:
print(e)
12. Write a program which will depict the usage of different functions of
‘re’
module. Make use of different pattern searching.
import re
s = 'Hey bro How Are You? '
match = re.search(r'bro', s)
print(f"Starting index :{match.start()}")
print(f"Ending index : {match.end()}")