You are on page 1of 31

Program 1: Write a function to find whether the given number is

perfect or not.

Description : A perfect number is a positive integer that is equal to the


sum of its positive divisors, excluding the number itself.
For example: 6 has divisors 1,2 and 3
Sum of divisors 1+2+3=6
so, 6 is a perfect number
The smallest perfect number is 6. Other perfect numbers are 28,496
and 8128

# To find whether a number is perfect or not


def perfect(num):

divsum=0
for i in range(1,num):
if num%i == 0:
divsum+=i
if divsum==num:
print('Perfect Number')

else:
print('Not a perfect number')
perfect(6)
perfect(15)

Output:
Perfect Number
Not a perfect number
Program 2: Write a function to find factorial of the entered number.

Description : The factorial of a number is the product of all the integers


from 1 to that number. Factorial is not defined for negative numbers and
factorial of 0 is 1 (0!=1)

Example: the factorial of 6 is 1*2*3*4*5*6 =720

#Program to calculate the factorial of given number


def fact(n):

f= 1
for i in range(1,n+1):

f = f*i
print("The factorial of ",num,"=",f)

num = int(input("Enter the number for calculating its factorial : "))


fact(num)

Output:
Enter the number for calculating its factorial : 5
The factorial of 5 = 120

Program 3: Write definition of a method EOSum(NUMBERS) to add


those values in the list of NUMBERS, which are odd and even.

def EOSum(numbers):
ec=0
oc=0
for i in numbers:
if i%2==0:
ec=ec+i
else:
oc=oc+i
print("sum of even is ",ec)
print("sum of odd is ",oc)
l=eval(input("enter list of numbers:"))
EOSum(l)
Output:
enter list of numbers:[1,2,3,4]
sum of even is 6
sum of odd is 4

Program 4: Write a function change(arr,n) which accepts a list of in-


tegers and its size as arguments and replaces elements having
even values with its half and elements having odd values with twice
its value.

def change(arr,n):
for i in range(n):
if arr[i]%2==0:
arr[i]=arr[i]//2
else:
arr[i]=arr[i]*2
print("The resultant array is ",arr)

l=eval(input("enter list of numbers :"))


change(l,len(l))
Output:
enter list of numbers :[32,45,2,78,5,7]
The resultant array is [16, 90, 1, 39, 10, 14]
Program 5: Write a function Display(num) in Python, which accepts
a list num and prints number which are ending with 0 in first line
and remaining numbers in second line.

def display(num):

l1=[]

l2=[]

for i in num:

if i%10==0:

l1.append(i)

else:

l2.append(i)

for i in l1:

print(i,end=' ')

print()

for j in l2:

print(j,end=' ')

l=eval(input("enter list of numbers:"))


display(l)

Output:
enter list of numbers:[1,3,4,80,50,20]
80 50 20
134
Program 6: Write a function count_words() to read data from file
“data.txt” and count occurrences of the given word in file
def count_words():
f=open("data.txt","r")
data=f.read()
words=data.split()
w=input("Enter the word to be searched:")
c=0
for i in words:
if i==w:
c=c+1
print("The word ",w,"occurs",c,"times")
f.close()
count_words()
If the content of the file data.txt is:
She started to work there
Right now, we looking forward to get you renowned

Output:
Enter the word to be searched:to
The word to occurs 2 times

Program 7: Write a method countM() in Python to read lines from a


text file ‘MYSTORY.TXT’, and display those lines, which are starting
with the alphabet ‘M’.

def countM():
fh=open("MYSTORY.TXT","r")
lines=fh.readlines()
for i in lines:
if(i[0]=='M'):

print(i)
fh.close()
countM()
If the “MYSTORY.TXT” contents are as follows:

My first journey to america


Myself vinayak.
Ensure to come first
Aware the things.
Mild think over it

Output

Count of lines starting with M is: 3

Program 8: Write a method/function Words() in Python to read con-


tents from a text file ZIP.TXT, to count and display the occurrence
of those words, which are having more than 4 alphabets.

def Words():
fh=open("ZIP.TXT","r")
data=fh.read()
w=data.split()
c=0
for i in w:
if(len(i)>4):
c=c+1

print(“Occurences of words which has more than 4 characters is",c)


fh.close()
Words()

If the content of the file is

She started to work there


Right now, we looking forward to get you renowned

Output

Occurences of words which has more than 4 characters is 7

Program 9: Write a function in Python that counts the number of


“Me” or “My” words present in a text file “STORY.TXT”.

def count():
fh=open("STORY.TXT","r")
data=fh.read()
w=data.split()
c=0
for i in w:
if(i=='Me' or i=='My'):
c=c+1
print("count of Me/My is ",c)
fh.close()
count()

If the “STORY.TXT” contents are as follows:

My best word is all right.


My friend is going to meet him.

Output:
Count of Me/My in file: 3
Program 10: Write a function AMCount() in Python, which should
read each character of a text file STORY.TXT, should count and
display the occurrences of alphabets A and M (including small cas-
es a and m too).

def AMcount():
fh=open("STORY.TXT","r")
data=fh.read()
acount=0
mcount=0
for i in data:
if(i=='M'or i=='m'):
mcount=mcount+1
if(i=='A' or i=='a'):
acount=acount+1
print("A or a :",acount)
print("M or m: ",mcount)
fh.close()
AMcount()

If the file content is as follows:


More apple and mango trees have to be grown

Output:

A or a: 4
M or m :2
Program 11:

Write a Python program to implement all basic operations of a stack,


such as adding element (PUSH operation), removing element (POP
operation) and displaying the stack elements (Traversal operation) us-
ing lists.
def push(s,item):
s.append(item)
def pop():
if len(s)==0:
return 'underflow'
else:
return s.pop()
def display():
if len(s)==0:
print("stack is empty")
else:
print("Elements of Stack are:")
for i in s:
print(i,end='\t')
print()

#Main program
s=[]
top=None
while True:
print("1.PUSH")
print("2.POP")
print("3.DISPLAY")
print("4.EXIT")
ch=int(input("enter choice:"))
if ch==1:
ele=int(input("enter element to be inserted:"))
push(s,ele)
elif ch==2:
val=pop()
if val=="underflow":
print("stack is empty")
else:
print("Deleted element is:",val)
elif ch==3:
display()
else:
break

OUTPUT:
1.PUSH
2.POP
3.DISPLAY
4.EXIT
enter choice:1
enter element to be inserted:23
1.PUSH
2.POP
3.DISPLAY
4.EXIT
enter choice:1
enter element to be inserted:34
1.PUSH
2.POP
3.DISPLAY
4.EXIT
enter choice:1
enter element to be inserted:67
1.PUSH
2.POP
3.DISPLAY
4.EXIT
enter choice:3
Elements of Stack are:
23 34 67
1.PUSH
2.POP
3.DISPLAY
4.EXIT
enter choice:2
Deleted element is: 67
1.PUSH
2.POP
3.DISPLAY
4.EXIT
enter choice:3
Elements of Stack are:
23 34
1.PUSH
2.POP
3.DISPLAY
4.EXIT
enter choice:5

Program 12:

Write a program to implement PUSH(N) and POP() where N is a list of in-


teger numbers. From this list push all numbers divisible by 3 into a stack
and display the values deleted from stack if it has at least one element,
otherwise display appropriate error message.
N=[12,43,56,6,26,42,39,17]
s=[]
def PUSH(N):
for x in N:
if x%3==0:
s.append(x)
if len(s)==0:
print("stack is empty")
else:
print("stack elements are: ",s)

def POP():
while True:
if len(s)!=0:
print(s.pop())
else:
return "underflow"

PUSH(N)
POP()

OUTPUT:
stack elements are: [12, 6, 42, 39]
39
42
6
12

Program 13:
Write a program to display unique vowels present in the given word
using Stack.

vowels =['a','e','i','o','u']
word = input("Enter the word to search for vowels :")
Stack = []
for letter in word:

if letter in vowels:
if letter not in Stack:
Stack.append(letter)
print(Stack)
print("The number of different vowels present in",word,"is",len(Stack))
OUTPUT:
Enter the word to search for vowels :python programming
['o', 'a', 'i']
The number of different vowels present in python programming is 3

\
14

Consider the following MOVIE table and write the SQL queries based
on it.

MovieID MovieName Category ReleaseDate ProductionCost BusinessCost

001 Hindi_Movie Musical 2018-04-23 124500 130000

002 Tamil_Movie Action 2016-05-17 112000 118000

003 English_Movie Horror 2017-08-06 245000 360000

004 Bengali_Movie Adventure 2017-01-04 72000 100000

005 Telugu_Movie Action - 100000 -

006 Punjabi_Movie Comedy - 30500 -

a) Create table and insert above data


mysql>create table MOVIE (MovieID int, MovieName
varchar(20), Category varchar(20), ReleaseDate date, Production-
Cost float, BusinessCost float);

OUTPUT:

Query OK, 0 rows affected (1.06 sec)

b) Display all the information from the Movie table

mysql> select * from MOVIE;

OUTPUT:

+---------+---------------+-----------+-------------+----------------+--------
------+

| MovieID | MovieName | Category | ReleaseDate | Produc-


tionCost | BusinessCost |

+---------+---------------+-----------+-------------+----------------+----------
----+

| 1 | hindi_movie | musical | 2018-04-23 | 124500 |


130000 |

| 1 | Tamil_movie | Action | 2016-05-17 | 112000 |


118000 |

| 3 | English_movie | Horror | 2017-08-06 | 245000 |


360000 |

| 4 | Bengali_movie | Adventure | 2017-01-04 | 72000


| 100000 |

| 5 | Telugu_movie | Action | NULL | 100000 |


NULL |

| 6 | Panjabi_movie | Comedy | NULL | 30500 |


NULL |
+---------+---------------+-----------+-------------+----------------+----------
----+

6 rows in set (0.02 sec)

c) List business done by the movies showing only MovieID, MovieN-


ame and Total_Earning. Total_ Earning to be calculated as the
sum of ProductionCost and BusinessCost.
mysql> select MovieID, MovieName, ProductionCost+BusinessCost as Total_Earning from
MOVIE;

OUTPUT:
+---------+---------------+---------------+

| MovieID | MovieName | Total_Earning |

+---------+---------------+---------------+

| 1 | hindi_movie | 254500 |

| 1 | Tamil_movie | 230000 |

| 3 | English_movie | 605000 |

| 4 | Bengali_movie | 172000 |

| 5 | Telugu_movie | NULL |

| 6 | Panjabi_movie | NULL |

+---------+---------------+---------------+

6 rows in set (0.00 sec)

d) List the different categories of movies.

mysql> select distinct category from MOVIE;

OUTPUT:

+-----------+

| category |

+-----------+

| musical |
| Action |

| Horror |

| Adventure |

| Comedy |

+-----------+

5 rows in set (0.04 sec)

d) Find the net profit of each movie showing its MovieID, MovieName
and NetProfit. Net Profit is to be calculated as the difference between
Business Cost and Production Cost.

mysql> select MovieID, MovieName, BusinessCost-ProductionCost as NetProfit from MOVIE;

output:

+---------+---------------+-----------+

| MovieID | MovieName | NetProfit |

+---------+---------------+-----------+

| 1 | hindi_movie | 5500 |

| 1 | Tamil_movie | 6000 |

| 3 | English_movie | 115000 |

| 4 | Bengali_movie | 28000 |

| 5 | Telugu_movie | NULL |

| 6 | Panjabi_movie | NULL |

+---------+---------------+-----------+

6 rows in set (0.00 sec)

15

Consider the following tables WORKERS and DESIG. Write SQL


commands for the statements (i) to (v)
i) Create Table WORKERS and DESIG with the attributes given in the
above table
mysql>CREATE TABLE WORKERS(W_ID INT,FIRSTNAME
VARCHAR(10),LASTNAME VARCHAR(10),GENDER
CHAR(1),ADDRESS VARCHAR(20),CITY VARCHAR(10));
output:
Query OK, 0 rows affected (0.80 sec)
mysql> CREATE TABLE DESIG(W_ID INT,SALARY
FLOAT,BENEFITS FLOAT,DESIGNATION VARCHAR(10));
OUTPUT:
Query OK, 0 rows affected (0.59 sec)
ii) Add Primary key constraint in WORKERS table
mysql> ALTER TABLE WORKERS ADD PRIMARY
KEY(W_ID);
output:
Query OK, 0 rows affected (0.94 sec)
Records: 0 Duplicates: 0 Warnings: 0
iii) Foreign key constraint in DESIG table

mysql>ALTER TABLE DESIG ADD FOREIGN KEY(W_ID) REF


ERENCES WORKERS(W_ID);
output:
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
iv) Insert above data in tables WORKERS and DESIG table
mysql> INSERT INTO WORKERS
VALUES(102,'Sam','Tones','M','33 Elm St’,'Paris');
output:
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO WORKERS


VALUES(105,'Sarah','Ackerman','F','U.S. 110','New
york’);
output:
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO WORKERS


VALUES(144,'Manila','Sengupta','F','24 Friends
Street','New Delhi’);

output:
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO WORKERS


VALUES(210,'George','Smith','M','83 First
Street','Howard');

output:
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO DESIG


VALUES(102,75000,15000,'Manager');

output:
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO DESIG


VALUES(105,85000,25000,'Director');

output:
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO DESIG


VALUES(144,70000,15000,'Manager');

output:
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO DESIG
VALUES(210,75000,12500,'Manager');
output:
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO DESIG


VALUES(400,32000,7500,'Salesman');

output:
ERROR 1452 (23000): Cannot add or update a child
row: a foreign key constraint fails
(`practical`.`desig`, CONSTRAINT `desig_ibfk_1`
FOREIGN KEY (`W_ID`) REFERENCES `workers`
(`W_ID`))

v) Delete record from workers table who lives in Paris.

mysql> DELETE FROM DESIG WHERE W_ID=102;

OUTPUT:

Query OK, 1 row affected (0.00 sec)

mysql> DELETE FROM WORKERS WHERE CITY=‘PARIS';

OUTPUT:

Query OK, 1 row affected (0.00 sec)


16

Consider the tables WORKERS and DESIG. Write SQL commands for
the statements

i) To display W_ID, Firstname, Address and City of all employees living


in New York from the table WORKERS
mysql> SELECT W_ID,FIRSTNAME,ADDRESS,CITY FROM
WORKERS WHERE CITY='NEW YORK’;
OUTPUT:
+------+-----------+------------------+----------
+
| W_ID | FIRSTNAME | ADDRESS | CITY
|
+------+-----------+------------------+----------
+
| 105 | Sarah | U.S. 110 | New york
|
| 403 | Ronny | 121 Harrison St. | New York
|
+------+-----------+------------------+----------
+
2 rows in set (0.00 sec)

ii) To display the content of WORKERS table in ascending order of


LASTNAME.
mysql> SELECT * FROM WORKERS ORDER BY LASTNAME;
OUTPUT:

+------+-----------+----------+--------+---------
----------+--------------+
| W_ID | FIRSTNAME | LASTNAME | GENDER | ADDRESS
| city |
+------+-----------+----------+--------+---------
----------+--------------+
| 105 | Sarah | Ackerman | F | U.S. 110
| New york |
| 255 | Mary | Jones | F | 842,
Vine Ave. | Losantiville |
| 403 | Ronny | Lee | M | 121 Har-
rison St. | New York |
| 300 | Robert | Samuel | M | 9 Fifth
Cross | Washington |
| 144 | Manila | Sengupta | F | 24
Friends Street | New Delhi |
| 210 | George | Smith | M | 83 First
Street | Howard |
| 451 | Pat | Thompson | M | 11 Red
Road | Paris |
| 102 | Sam | Tones | M | 33 Elm
St | Paris |
| 335 | Henry | Williams | M | 12 Moore
Street | Boston |
+------+-----------+----------+--------+---------
----------+--------------+
9 rows in set (0.00 sec)

iii) To display First Name, Worker ID and Address of male Workers only.
mysql> SELECT FIRSTNAME,W_ID,ADDRESS FROM WORK-
ERS WHERE GENDER=‘M';
OUTPUT:
+-----------+------+------------------+
| FIRSTNAME | W_ID | ADDRESS |
+-----------+------+------------------+
| Sam | 102 | 33 Elm St |
| George | 210 | 83 First Street |
| Robert | 300 | 9 Fifth Cross |
| Henry | 335 | 12 Moore Street |
| Ronny | 403 | 121 Harrison St. |
| Pat | 451 | 11 Red Road |
+-----------+------+------------------+
6 rows in set (0.00 sec)

iv) To display the Minimum salary among Managers and Clerks from the
table DESIG.
mysql> SELECT DESIGNATION,MIN(SALARY) FROM DESIG
GROUP BY DESIGNATION HAVING DESIGNATION IN
(‘CLERK','MANAGER');

OUTPUT:
+-------------+-------------+
| DESIGNATION | MIN(SALARY) |
+-------------+-------------+
| Manager | 70000 |
| Clerk | 40000 |
+-------------+-------------+
2 rows in set (0.00 sec)

v) To display First Name and Salary from Workers and Desig Table for
each worker.
mysql> SELECT W.FIRSTNAME,D.SALARY FROM WORKERS
W,DESIG D WHERE W.W_ID=D.W_ID;

OUTPUT:

+-----------+--------+
| FIRSTNAME | SALARY |
+-----------+--------+
| Sarah | 85000 |
| Manila | 70000 |
| George | 75000 |
| Sam | 75000 |
| Mary | 50000 |
| Robert | 45000 |
| Henry | 40000 |
| Pat | 28000 |
+-----------+--------+
8 rows in set (0.00 sec)

17

Consider the table Books given below. Write SQL Commands for the
statements

i) To Create table and insert data


mysql> CREATE TABLE BOOKS(BOOK_ID INT,BOOK_NAME
VARCHAR(20),AUTHOR_NAME VARCHAR(20),PUBLISHERS VAR-
CHAR(20),PRICE FLOAT,QTY INT);
OUTPUT:
Query OK, 0 rows affected (0.02 sec)

mysql> CREATE TABLE BOOKS(BOOK_ID INT,BOOK_NAME


VARCHAR(20),AUTHOR_NAME VARCHAR(20),PUBLISHERS
VARCHAR(20),PRICE FLOAT,QTY INT);

OUTPUT:
Query OK, 0 rows affected (0.02 sec)

mysql> INSERT INTO BOOKS VALUES(1001,'The


Human','J P Singh','TDH',550,10);

OUTPUT:
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO BOOKS VALUES(1002,'Ninety


Nine','W P Ram','EPB',700,5);

OUTPUT:
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO BOOKS VALUES(1003,'Fast


Cook','Lata Kapoor','Sagar',650,2);

OUTPUT:
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO BOOKS VALUES(1004,'Vidur','H P


Nayak','Hillman',250,7);

OUTPUT:
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO BOOKS VALUES(1005,'Officer','K
Prakash','EPB',370,11);

OUTPUT:
Query OK, 1 row affected (0.00 sec)

ii) To display the average price of books which quantity is grater than 5
from the table Books
mysql> SELECT AVG(PRICE) FROM BOOKS WHERE QTY>5;
OUTPUT:
+------------+
| AVG(PRICE) |
+------------+
| 390 |
+------------+
1 row in set (0.00 sec)
iii) To display Book name, publishers of books where publisher name
starts with T
mysql> SELECT BOOK_NAME,PUBLISHERS FROM BOOKS
WHERE PUBLISHERS LIKE ’T%';

OUTPUT:
+-----------+------------+
| BOOK_NAME | PUBLISHERS |
+-----------+------------+
| The Human | TDH |
+-----------+------------+
1 row in set (0.00 sec)
iv) To display sum of price from BOOKS table
mysql> SELECT SUM(PRICE) FROM BOOKS;
OUTPUT:
+------------+
| SUM(PRICE) |
+------------+
| 2520 |
+------------+
1 row in set (0.00 sec)

18

Write a python program to create the following table HRD

import mysql.connector
con=mysql.connector.connect(user='root',password='jnvegh794111',host='l
ocalhost',
database='user')

cur=con.cursor()
stmt = "CREATE TABLE HRD(Ecode int primary key, Ename
varchar(25), Designation varchar(20), Remuneration float);”
cur.execute(stmt)

con.commit()
con.close()

OUTPUT:
mysql> DESC HRD;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| ECODE | int | YES | | NULL | |
| ENAME | varchar(20) | YES | | NULL | |
| DESIGNATION | varchar(20) | YES | | NULL | |
| RENUMERATION | float | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

19 . Write a python program to insert one record from the following


table HRD
import mysql.connector
con=mysql.connector.connect(user='root',password='jnvegh794111',host='l
ocalhost',
database='user')

cur=con.cursor()
Stmt = "INSERT INTO HRD VALUES (10001,’Vipul’,’Programmer',
50000);"
cur.execute(stmt)

con.commit()
con.close()

OUTPUT:
mysql> SELECT * FROM HRD;
+-------+-------+-------------+--------------+
| ECODE | ENAME | DESIGNATION | REMUNERATION |
+-------+-------+-------------+--------------+
| 10001 | Vipul | Programmer | 50000 |
+-------+-------+-------------+--------------+
1 row in set (0.00 sec)

20. Write a python program to fetch records from the HRD table having remunera-
tion more than 70000

import mysql.connector
con=mysql.connector.connect(user='root',password='jnvegh794111',host='l
ocalhost',
database='user')
cur=con.cursor()
Stmt = "SELECT * FROM HRD WHERE REMUNERATION > 70000;"
try:
cur.execute(stmt)
resultset = cur.fetchall()
for row in resultset:
print (row)
except:
print ("Error: unable to fetch data")
con.close()

OUTPUT:

21. Write a python program to update remuneration of employee to 70000 from the
HRD table whose name is Vipul

import mysql.connector
con=mysql.connector.connect(user='root',password='jnvegh794111',host='l
ocalhost',
database='user')
cur=con.cursor()
Stmt = "UPDATE HRD SET REMUNERATION=70000 WHERE
ENAME=‘VIPUL';"
try:
cur.execute(stmt)
cur.commit()
except:
print(“Unable to update data”)
con.close()

OUTPUT:
mysql> SELECT * FROM HRD;
+-------+-------+-------------+--------------+
| ECODE | ENAME | DESIGNATION | RENUMERATION |
+-------+-------+-------------+--------------+
| 10001 | Vipul | Programmer | 70000 |
+-------+-------+-------------+--------------+
1 row in set (0.00 sec)

You might also like