Final Python Journal 112
Final Python Journal 112
53003190112
INDEX
Sr. no Titles of Practical Page
1.a To create a program that asks the user to enter their name 4
and their age.Print out a message addressed to them that tells them the
year that they will turn 100 years old.
1.b To enter the number from the user and depending on whether the number
is even or odd, print out an appropriate message to the user.
1.c To write a program to generate a fibonacci series.
1.d To write a function that reverses the user define value
1.e To write a function to check the input value is Armstrong and also write
the function for Palindrome.
1.f To write a recursive function to print the factorial for a given numbers.
2.a To write a function that takes a character (i.e. a string of length 1) and 10
returns true if its is vowel,False otherwise.
2.b To write a function that computes the length of a string or a list.
2.c To define a procedure histogram() that takes a list of integers and prints a
histogram to the screen. For example , histogram([4,9,7]) should print the
following:
****
*********
*******
3.a To write a function to check a sentence to see if it is a pangram or not. 13
3.b To write a program that prints out all the elements of the list that are less
than 5.
4.a To write a program that takes two list and returns True if they 15
have atleast one common member.
4.b To write a python program to print a specified list after removing the list
0th ,2nd,4th,and 5th elements.
4.c To write a python program to clone or copy a list
5.a To write a python script to concatenate following dictionary to create a 17
new one.
5.b To write a python script to concatenate following dictionary to create a
new one.
5.c To write a python program to sum all the items in a dictionary.
6.a To write a python program to read an entire text file 19
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
6.b To write a python program to append text to a file and display the text
6.c To write a python program to read last n lines of a file.
7.a To design a class that store the information of student and display. 22
i. Write a method called add which returns the sum of the attributes x and
y.
ii. Write a class method called multiply, which takes a single number
parameter a and returns the product of a and MULTIPLIER.
iii. Write a static method called subtract, which takes two number
parameters, b and c, and returns b - c.
iv. Write a method called value which returns a tuple containing the
values of x and y. Make this method into a property, and write a setter and
a deleter for manipulating the values of x and y.
8.a. Open a new file in IDLE (“New Window” in the “File” menu) and save it 27
as geometry.py in the directory where you keep the files you create for
this course. Then copy the functions you wrote for calculating volumes
and areas in the “Control Flow and Functions” exercise into this file and
save it.
Now open a new file and save it in the same directory. You should now be
able to import your own module like this:
importgeometry
Try and add print dir(geometry) to the file and run it.
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
9.a. Try to configure the widget with various options like: bg=”red”, 30
family=”times”, size=18.
9.b. Try to change the widget type and configuration options to experiment
with other widget types like Message, Button, Entry, Checkbutton,
Radiobutton, Scale etc.
10.a. Design a simple database application that stores the records and retrieve 34
the same.
10.b. Design a database application to search the specified record from the
database.
10.c. Design a database application to that allows the user to add, delete and
modify the records.
PYTHON
1st Practical [A]
Aim- Create a program that asks the user to enter their
name and their age. Print out a message addressed to them
that tells them the year that they will turn 100 years old.
CODE:
import datetime
name = input("Hello! Please enter your name: ")
print("Hello " + name)
age = int(input("Enter your age: "))
year_now = datetime.datetime.now()
# print(year_now.year)
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
1st Practical[B]
Aim-Enter the number from the user and depending on
whether the number is even or odd, print out an appropriate
message to the user.
CODE :
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
else:
print("{0} is Odd".format(num)
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
n2 = nth
count += 1
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
CODE:
# Python Program to Reverse a Number using While loop by using function
def reverse_number(number):
reverse = 0
reverse_number(11184756392856487)
OUTPUT:
def armstrong(num):
sum=0
temp = num
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
else:
def palindrome(num):
n = num
rev = 0
while num != 0:
rev = rev * 10
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
if n == rev:
else:
armstrong(num)
palindrome(num)
OUTPUT:
CODE:
# Python program to find the factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
if num < 0:
elif num == 0:
else:
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 2[A]
A. Write a function that takes a character (i.e. a string of length 1) and
returns True if it is a vowel, False otherwise.
Code:
def find_vowel(s):
l=['a','e','i','o','u']
for i in s:
if i in l:
print('true')
else:
print('false')
s='god is great'
find_vowel(s)
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 2[B]
[B] Define a function that computes the length of a given list or string.
CODE:
def len_s(s):
count=0
for i in s:
if i !='':
count+=1
s='god is great'
len_s(s)
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 2[C]
[C] Define a procedure histogram() that takes a list of integers and prints a histogram to the
screen. For example, histogram([4, 9, 7]) should print the following:
****
*********
*******
CODE:
l = [2, 4, 5]
def histogram(l):
for i in l:
print('*'*i)
histogram(l)
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 3[A]
[A] AIM: A pangram is a sentence that contains all the letters of the English
alphabet at least once, for example: The quick brown fox jumps over the lazy
dog. Your task here is to write a function to check a sentence to see if it is a
pangram or not.
CODE:
if sys.version_info[0] < 3:
input = raw_inp
alphaset = set(alphabet)
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 3[B]
Aim: Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less
than 5.
CODE:
l1=[1,1,2,3,5,8,13,21,34,55,89]
l2=[]
for i in l1:
if i <5:
l2.append(i)
print (l2)
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 4[A]
AIM: Write a program that takes two lists and returns True if they have at
least one common member.
CODE:
11=[1,2,3,4,5,6,]
l2=[11,12,13,14,15,6]
for i in l1:
for j in l2:
if i==j:
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 4[B]
AIM: Write a Python program to print a specified list after removing the 0th,
2nd, 4th and 5th elements.
CODE:
1=[1,2,3,4,5,6,7,8,9,0]
l1.remove(l1[0]) #this line will remove 1 from the list, Therefore l1[0]=2
l1.remove(l1[1])
print("After Removal of 1st element of New List (original 2nd index element)
is",l1)
l1.remove(l1[2])
print("After Removal of 3rd element of New List (original 4th index element)
is",l1)
l1.remove(l1[2])
print (l1)
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 4[C]
AIM: Write a Python program to clone or copy a list.
CODE:
11=[2, 4, 7, 8, 9, 0]
l2=l1
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 5[A]
AIM: Write a Python script to sort (ascending and descending) a dictionary by
value.
CODE:
print (key,value)
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 5[B]
AIM: Write a Python script to concatenate following dictionaries to create a new
one.Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40}
dic3={5:50,6:60}Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50,
6: 60}
CODE:
dic1={1:10,2:20}
dic2={3:30,4:40}
dic3={5:50,6:60}
dic1.update(dic2)
print (dic1)
dic1.update(dic3)
print (dic1)
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 5[C]
AIM: Write a Python program to sum all the items in a dictionary.
CODE:
my_dict = {'data1':10,'data2':20,'data3':30}
print(sum(my_dict.values()))
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
PRACTICAL 6[A]
Write the program for the following: (File handling)
CODE:
def file_read(fname):
txt = open(fname)
print(txt.read())
file_read('practical6.txt')
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 6[B]
AIM: Write a Python program to append text to a file and display the text.
CODE:
def file_read(fname):
myfile.write("Python Exercises\n")
myfile.write("Java Exercises")
txt = open(fname)
print(txt.read())
file_read('practical6.txt')
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 6[C]
AIM: Write a Python program to read last n lines of a file.
CODE:
import sys
import os
def file_read_from_tail(fname,lines):
bufsize = 8192
fsize = os.stat(fname).st_size
iter = 0
with open(fname) as f:
if bufsize>fsize:
bufsize = fsize-1
data = []
while True:
iter +=1
f.seek(fsize-bufsize*iter)
data.extend(f.readlines())
print(''.join(data[-lines:]))
break
file_read_from_tail('practical6.txt',2)
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 7[A]
AIM:Design a class that store the information of student and display the
CODE:
sameclass student:
def disp(self,Name,Sapid,Gender,Course):
self.Name=Name
self.Sapid=Sapid
self.Gender=Gender
print ('Name:',Name)
print ('Sapid:',Sapid)
print ('Gender:',Gender)
print ('Course:',Course)
s1=student()
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 7[B]
AIM: Implement the concept of inheritance using python
CODE:
class Shape:
def _init_(self,x,y):
self.x=x
self.y=y
def area(self,x,y):
self.x=x
self.y=y
a=self.x*self.y
print (author)
def _init_(self,x):
self.x=x
def area(self,x):
self.x=x
a= self.x*self.x
print('Area of a square',a)
OUTPUT:
class Shape:
def _init_(self,x,y):
self.x=x
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
self.y=y
def area(self,x,y):
self.x=x
self.y=y
a=self.x*self.y
print('Area of a rectangle',a);
class Square(Shape):
def _init_(self,x):
self.x=x
def area(self,x):
self.x=x
a= self.x*self.x
print('Area of a square',a)
r=Shape()
r.area(12,34)
s=Square()
s.area(34)
Output:-
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 7[C]
AIM:. 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).
Write a method called add which returns the sum of the attributes x and y.
Write a class method called multiply, which takes a single number parameter a
and returns the product of a and MULTIPLIER.
Write a static method called subtract, which takes two number parameters, b
and c, and returns b - c.
Write a method called value which returns a tuple containing the values of x and
y. Make this method into a property, and write a setter and a deleter for
manipulating the values of x and y.
CODE:
class Numbers(object):
def _init_(self,x,y):
self.x=x
self.y=y
def add(self,x, y):
self.x=x
self.y=y
return self.x+self.y
def multiply(self,x):
MULTIPLIER=7.4
self.x=x
return self.x*MULTIPLIER
@staticmethod
def subtract(self,x,y):
self.x=x
self.y=y
return self.x-self.y
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 8[A]
AIM:
Open a new file in IDLE (“New Window” in the “File” menu) and save it as
geometry.py in the directory where you keep the files you create for this course.
Then copy the functions you wrote for calculating volumes and areas in the
“Control Flow and Functions” exercise into this file and save it.
Now open a new file and save it in the same directory. You should now be able
to import your own module like this:
importgeometry
Try and add print dir(geometry) to the file and run it.
CODE:
geometry.py
def circleArea(r):
PI = 3.142
return PI * (r*r);
def squareArea(s):
return s*s;
main.py
import geometry
if square:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
base = geometry.squareArea(x)
else:
base = geometry.circleArea(x)
print("Area of Circle:",geometry.circleArea(2))
print("Area of Square:",geometry.squareArea(2))
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 8[B]
AIM:
CODE:
class InvalidData(Exception):
self.data=data
def errorMsg(self):
v=InvalidData(number)
try:
if number<10 or number>20:
raise v
except InvalidData:
print(v.errorMsg())
OUTPUT:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 9[A]
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
AIM: Try to configure the widget with various options like: bg=”red”,
family=”times”, size=18.
CODE:
import tkinter
root=Tk()
n = Label(root,text="Welcome",font=('Verdana',20))
O.pack()
n.pack()
root.mainloop()
OUTPUT:
Practical 9[B]
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
AIM: Try to change the widget type and configuration options to experiment
with other widget types like Message, Button, Entry, Checkbutton, Radiobutton,
Scale etc.
CODE:
import tkinter as t
import tkinter.font as f
mf=t.Tk()
mf.geometry('100x100')
#message
msgctrl.grid(row=0,column=3)
#entry#Label
lbl1.grid(row=1,column=2)
e1.grid(row=1,column=3)
# text box
#Label
lbl2.grid(row=2,column=2)
txt1=t.Text(mf,height=5, width=20)
txt1.grid(row=2,column=3)
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
#radiobutton
#Label
lbl3.grid(row=4,column=2)
def rb_show():
rv1 = t.IntVar()
#rv1.set(1)
#rv2 = t.IntVar()
rb1.grid(row=4,column=3)
rb2.grid(row=4,column=4)
#checkbox code
#Label
lbl3.grid(row=5,column=2)
v1=t.BooleanVar()
v2=t.IntVar()
chk2=t.Checkbutton(mf,text="Dancing", variable=v2)
v3=t.IntVar()
chk3=t.Checkbutton(mf,text="Reading", variable=v3)
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
chk1.grid(row=5,column=3)
chk2.grid(row=5,column=4)
chk3.grid(row=5,column=5)
# button demo
def disp():
b1.grid(row=7,column=3)
mf.mainloop()
Output:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 10[A]
AIM: Design a simple database application that stores the records and retrieve the same.
CODE:
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')
LAST_NAME CHAR(20),
AGE INT,
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
# disconnect from server
db.close()
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='p
ython_mysql')
# Prepare SQL query to INSERT a record into the database. sql = """INSERT INTO
EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
cursor.execute(sql) print ("Data Inserted Successfully...!") # Commit your changes in the
database db.commit() except:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Practical 10[B]
AIM:Design a database application to search the specified record from the database.
CODE:
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')
cursor.execute(sql)
# Fetch all the rows in a list of lists. results = cursor.fetchall() for row in results:
fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4]
print ("Fname=%s,Lname=%s,Age=%d,Sex=%s,Income=%d" % \
(fname, lname, age, sex, income )) except: print ("Error: unable to fecth data")
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
db.close()
Practical 10[C]
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
AIM: Design a database application to that allows the user to add, delete and modify the
records. DataAdd.py
CODE:
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \ ('Ashwin', 'Mehta', 23, 'M', 22000) try:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
db.close()
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
# prepare a cursor object using cursor() method cursor = db.cursor()
# Prepare SQL query to UPDATE required records sql = "DELETE FROM EMPLOYEE WHERE
AGE < '%d'" % (20) try:
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
Update.py
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')
# Prepare SQL query to UPDATE required records sql = "DELETE FROM EMPLOYEE WHERE
AGE < '%d'" % (20) try:
db.close()
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112
RAJ VADHAN
53003190112