Deepak python practical file
Deepak python practical file
PRACTICAL FILE
Subject Code-BS-DSE5.4
Name of Subject- PYTHON
Course :- Bsc.it
Semester :-6th
(School of CA & IT)
1. Programs on string 1
3. Program on Lists 16
4. Programs on Sets 23
5. Programs on Dictionary 26
6. Programs on Functions 30
9. Programs on Sqlite 39
PROGRAMS ON STRING
Q.3 Write a python program to get a string made of the first 2 and
the last 2 characters from a given string. If the string is less than 2,
return instead of the empty string.
Ans a=input(“enter the string: ”)
If len(a)>=2
x=a[0:2]
y=a[len(a)-2:len(a)]
print("the string made of the first and last two character of the
given string:",x+y)
else:
print(“ “)
O/P:
Q.4 Write a python program to get a string from a given string where
all occurrence of its first character have been changed to ‘$’ except
the first character listed.
Ans x=input(“enter the string: ”)
char=x[0]
x=x.replace(char, ‘$’)
x=char+x[1:]
print(x)
O/P:
Q.5 Write a python program to get a single string from two given
strings, separated by a space and swap their first two characters.
Ans x=input(“enter the first string: “)
y=input(“enter the second string: “)
a=y[:2]+x[2:]
b=x[:2]+y[2:]
print(a+” “+b)
O/P:
Q.6 Write a python program to add ‘ing’ at the end of the string
(length should be at least 3). If the given string already ends with
‘ing’ then add ‘ly’ instead. If the string length pf the given string is
less than 3, leave it unchanged.
Ans x=input(“enter the string: “)
if len(a)>=3:
if “ing” not in a:
print(a+”ing”)
else:
print(a+”ly”)
else:
print(a)
O/P:
O/P:
Q.8 Write a python program that takes a list of words and returns
the length of the longest one.
Ans a=input(“enter the list of the string: ”)
n=a.split()
lo=len(n[0])
for i in n:
if(len(i)>lo):
lo=len(i)
print(“the length of the longest word is: “, lo)
O/P:
Q.9 Write a python program to remove the nth index character from
a non-empty string.
Ans a=input(“enter the string: “)
n=int(input(“enter the index no. which is to be remove “)
x=a[:n]
y=a[n+1:]
print(x+y)
O/P:
O/P:
y=x.ljust(10)
print(y)
O/P:
y=x.rjust(10)
print(y)
O/P:
O/P:
Q.19 Write a python program to find the first non-repeating
character in a given string.
Ans def func(x)
c=[ ]
f={ }
for i in x:
if i in f:
f[i]+=1
else:
f[i]=1
c,append(i)
for i in c:
if f[i]==1
return(i)
return(“none”)
x=input(“enter the string: “)
func(x)
O/P:
O/P:
Q.22 Write a python program to create a string from two given string
concatenating uncommon characters of the said string.
Ans x=input(“enter the first string: “)
y=input(“enter the second string: “)
set1=set(x)
set2=set(y)
common_chars=list(set1&set2)
result=[ch for ch in x if ch not in common_chars]+ [ch for ch in y if ch
not in common_chars]
print(‘’,join(result))
O/P:
Q.23 Write a python program to count uppercase, lowercase, special
characters and numeric characters in a given string.
Ans x=input(“enter the string: “)
Upper, lower, special, numeric=0, 0, 0, 0
for i in x:
if i>=’A’ and i<=’Z’
upper+=1
elif i>=’a’ and i<=’z’
lower+=1
elif i>=’0’ and i<=’9’
numeric+=1
else:
special+=1
print(“uppercase characters: ” +str(upper))
print(“lowercase characters: ” +str(lower))
print(“numeric characters: “ +str(numeric))
print(“special characters: “ +str(special))
O/P:
O/P:
Programs on For loop
O/P
O/P:
Q.3. Write a program to determine whether a given natural
number is a perfect number. A natural number is said to be
perfect number if it is the sum of its devisors. For example, 6
is a perfect number because 6=1+2+3, but 15 is not a perfect
number because 15 ≠ 1+3+5
Ans: n = int(input("Enter any number: "))
sum = 0
for i in range(1, n):
if(n % i == 0):
sum = sum + i
if (sum == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")
O/P:
O/P:
Program on Lists
Q.1 Write a python program to get the largest and second largest
number from a list.
Ans x=[‘21’, ‘11’, ‘15’, ‘51’]
y=max(x)
print(“the largest no. is”,y)
x.remove(y)
z=max(x)
print(“the second largest no, is “, z)
O/P:
O/P:
O/P:
O/P:
O/P:
Q.8 Write a python program to get unique values from a list.
Ans lst=[‘13’, ‘15’, ‘17’, ‘34’, ‘11’, ‘15’, ‘17’]
my_set=set(lst)
my_newlist=list(my_set)
print(my_newlist)
O/P:
O/P:
Q.10 Write a python program to check whether a list contains a
sublist.
Ans lst=['23', '14', '21', '11', '15', '23', '11']
sub=['23', '14', '21']
sub_set=False
if sub==[]:
sub_set=True
elif sub==1:
sub_set=True
elif len(sub)>len(lst):
sub_set=True
else:
for i in range(len(lst)):
if lst[i]==sub[0]:
n=1
while(n<len(sub)) and (lst[i+n]==sub[n]):
n+=1
if n==len(sub):
sub_set=True
print(sub_set)
O/P:
Q.11 Write a python program to find common items from the two
lists.
Ans color1=[“Red”, “Blue”, “Pink”, “Green”]
color2=[“Yellow”, “White”, “Blue”, “Red”]
print(set(color1) & set(color2))
O/P:
Q.12 Write a python program to convert a list of multiple integers
into a single string.
Ans mylist=['23', '14', '21', '11', '15', '23', '11']
y=””.join(mylist)
print(y)
O/P:
O/P:
Q.14 Write a python program to find the list in a list whose sum of
the elements is the highest.
Ans num=[[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]]
print(max(num, key=sum))
O/P:
Q.15 Write a python program to remove duplicates from a list of
lists.
Ans num=[[‘10’, ‘20’],[‘40’], [‘30’, ‘56’, ‘25’], [‘10’, ‘20’], [‘33’], [‘40’]]
new_num=[]
for elem in num:
if elem not in new-num:
new_num.append(elem)
num=new_num
print(new_num)
O/P:
O/P:
Q.17 write a python program to remove consecutive duplicates of a
given list.
Ans lis=[‘0’, ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘4’, ‘5’, ‘6’, ‘6’, ‘7’, ‘8’, ‘9’, ‘4’, ‘4’]
i=0
while i<len(lis)-1:
if lis[i]==lis[i+1]:
del lis[i]
else:
i+=1
print(lis)
O/P:
O/P:
Programs on Sets
O/P:
O/P:
for intersection
n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
nm=n&m
print(“the intersection of two sets is: “, nm)
for difference:
n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
nm=n-m
print(“the difference of the two sets is: “, nm)
for symmetric_difference:
n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
nm=n^m
print(“the symmetric difference of the two sets is: “, nm)
O/P:
O/P:
Q.6 Write a python program to check if two given sets have no
elements in common.
Ans n=set(input("enter the first set").split())
m=set(input("enter the second set").split())
if n.isdisjoint(m):
print("no in the two sets none of the elements are
common")
else:
print("yes in the two sets some of the elements are
common")
O/P:
O/P:
Program on Dictionary
O/P:
O/P:
O/P:
Q.4 Write a python program to generate and print a dictionary that
contains a number(between 1 and n) in the form (x, x*x).
Ans n=int(input("enter the no. "))
d=dict()
for x in range(1, n+1):
d[x]=x*x
print(d)
O/P:
Q.5 Write a python program to print a dictionary where the keys are
numbers between 1 and 15(both included) and the values are the
squares of keys.
Ans d=dict()
for x in range(1, 16):
d[x]=x*x
print(d)
O/P:
O/P:
Q.7 Write a python program to sum and multiply all the items in a
dictionary.
Ans my_dict={'data1': 100, 'data2': 200, 'data3':300}
print(sum(my_dict.values()))
O/P:
O/P:
O/P:
O/P:
Q.10 Write a python program to combine two dictionary adding
values for common keys.
Ans my_dict1={'data2': 100, 'data3': 200, 'data1':100, 'data4':100}
my_dict2={'data2': 100, 'data1': 200, 'data3':300}
for i in my_dict2:
if i in my_dict1:
my_dict1[i]=my_dict1[i]+my_dict2[i]
else:
my_dict1[i]=my_dict2[i]
print(my_dict1)
O/P:
O/P:
O/P:
Program on Functions
O/P:
O/P:
O/P:
Q.3 Write a python program to count the even, odd numbers in a
given array of integers using lambda.
Ans lst=[2, 4, 6, 8, 9, 11, 15]
print("the original list is ", lst)
odd_ctr=len(list(filter(lambda x:(x%2!=0), lst)))
even_ctr=len(list(filter(lambda x:(x%2==0), lst)))
print("the no. of even numbers in the list is ", even_ctr)
print("the no. of odd numbers in the list is ", odd_ctr)
O/P:
Q.4 Write a python program to add two given lists using map and
lambda.
Ans lst1=[2, 4, 6, 8, 9, 11, 15]
lst2=[3, 6, 7, 8, 3, 2, 1]
print("the first list is: ", lst1)
print("the second list is: ", lst2)
add_list=map(lambda x, y:x+y, lst1, lst2)
print("the sum of the two given lists are ", list(add_list))
O/P:
Q.5 Write a python program to calculate the sum of the positive and
negative numbers of a given list of numbers using lambda function.
Ans lst1=[-2, 4, -6, 8, 19, 10, -1]
lst2=[3, -6, 4, -8, -3, -2, 1]
print("the first list is: ", lst1)
print("the second list is: ", lst2)
add_list=map(lambda x, y:x+y, lst1, lst2)
print("the sum of the two given lists are ", list(add_list))
O/P:
O/P:
Q.4 Write a python program to sort a list of elements using the linear
search algorithm.
Ans: lst = []
num = int(input("Enter size of list :- "))
for n in range(num):
numbers = int(input("Enter the array of %d element :- "
%n))
lst.append(numbers)
x = int(input("Enter number to search in list :- "))
i=0
flag = False
for i in range(len(lst)):
if lst[i] == x:
flag = True
break
if flag == 1:
print('{} was found at index {}.'.format(x, i))
else:
print('{} was not found.'.format(x))
O/P:
O/P:
Program on Sqlite
Doctor
HOSPITAL
Hospital_Id(P) Doctor_Id(P)
Hospital_Name Doctor_Name
Bed_count Hospital_Id(F)
Joining_Date
Speciality
Salary
Experience
O/P:
import sqlite3
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
cr.execute("create table DOCTOR(Doctor_id integer Primary key
,Doctor_Name Text not null, Hospital_id integer not null,
Speciality text not null, salary integer not null, Experience
integer)");
conn.commit()
print("TABLE DOCTOR is created")
O/P:
Q.2. Insert records in tables hospital and Doctor by taking input from
user.
Ans. import sqlite3
conn=sqlite3.connect('manisha.db')
cr=conn.cursor()
Hospital_id=int(input("Enter Hospital_id: "))
HOspital_name=input("Enter Name Of The Hospital: ")
Bed_count=int(input("Enter Bed count: "))
cr.execute("""INSERT INTO
HOSPITAL(Hospital_id,HOspital_name,Bed_count)VALUES(?,?,?);""",(Hospital_id,Hos
pital_name,Bed_count))
cr.execute("""INSERT INTO
HOSPITAL(Hospital_id,HOspital_name,Bed_count)VALUES(?,?,?);""",(Hospital_id,Hos
pital_name,Bed_count))
cr.execute("""INSERT INTO
HOSPITAL(Hospital_id,HOspital_name,Bed_count)VALUES(?,?,?);""",(Hospital_id,Hos
pital_name,Bed_count))
cr.execute("""INSERT INTO
HOSPITAL(Hospital_id,HOspital_name,Bed_count)VALUES(?,?,?);""",(Hospital_id,Hos
pital_name,Bed_count))
cr.execute("""INSERT INTO
HOSPITAL(Hospital_id,HOspital_name,Bed_count)VALUES(?,?,?);""",(Hospital_id,Hos
pital_name,Bed_count))
conn.commit()
O/P:
import sqlite3
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
Doctor_id=int(input("Enter doctor_id: "))
Doctor_name=input("Enter Name Of The Doctor: ")
Hospital_id=int(input("Enter Hospital_id: "))
Speciality=input("enter speciality: ")
Experience=int(input("Experience: "))
salary=int(input("salary: "))
cr.execute("""INSERT INTO
DOCTOR(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary)VALUES
(?,?,?,?,?,?);""",(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary))
cr.execute("""INSERT INTO
DOCTOR(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary)VALUES
(?,?,?,?,?,?);""",(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary))
cr.execute("""INSERT INTO
DOCTOR(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary)VALUES
(?,?,?,?,?,?);""",(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary))
cr.execute("""INSERT INTO
DOCTOR(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary)VALUES
(?,?,?,?,?,?);""",(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary))
cr.execute("""INSERT INTO
DOCTOR(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary)VALUES
(?,?,?,?,?,?);""",(Doctor_id,Doctor_name,Hospital_id,Speciality,Experience,salary))
conn.commit()
O/P:
Q.3 Fetch the information of the tables Hospital and Doctor.
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
rows=cr.fetchall()
print(row)
conn.commit()
O/P:
import sqlite3
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
cr.execute("select* from HOSPITAL")
rows=cr.fetchall()
for row in rows:
print(row)
conn.commit()
O/P:
Q.4. Get the list of doctors as per the given speciality and salary.
Fetch all doctors whose salary is higher than the input amount and
speciality is the same as the input speciality.
Ans. import sqlite3
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
n=int(input("enter the input salary: "))
cr.execute("select Doctor_name from DOCTOR where salary >
%d"%n)
rows=cr.fetchall()
for row in rows:
print(row)
conn.commit()
O/P:
import sqlite3
conn=sqlite3.connect('mydb.db')
cr=conn.cursor()
n=input("enter the speciality ")
cr.execute("select Doctor_name from DOCTOR where
Speciality=='%s'" %n)
rows=cr.fetchall()
for row in rows:
print(row)
conn.commit()
O/P: