Python
Python
Python
Shukla
Resource person
Prof.Kiran Gurbani
(HOD, IT & CS Department, RKT College of Arts, Science & Commerce)
S.Y.BSc.IT
SEMESTER-III
PYTHON PROGRAMMING
PRACTICAL
MANUAL
2017-2018
Compiled By:
PROF. KIRAN GURBANI
&
PROF.NITESH N. SHUKLA
Installation Step for Python 3.4.x and MySQL Connectivity to Python 3.4.x
1. Double Click on the Python 3.4.3
2. Click Next
3. Click Next
4. Click Next
6.Click Finish
19. Enter password–“ password” It will be used in database connection and click on Next button
Now Install Mysql Connector for Python 3.4. Click on the Following
Windows Installer File.
10. Now Check the MySQL Connectivity is done or not by Opening the
IDLE (Python 3.4 GUI).
TestDB.py
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',datab
ase='nit')
# prepare a cursor object using cursor()
method cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : %s " % data)
# disconnect from server
db.close()
Practical No.1
1. Write the program for the following: (by using control statements
and control structure)
A. 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)
print("You will turn 100 in " + str(int(100-age) + int(year_now.year)))
Output
B. 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 :
Output:-
Code:
Output
Python code :
def reverse_number(number):
reverse = 0
while(number > 0):
reminder = number %10
reverse = (reverse *10) + reminder
number = number //10
print("Reverse number is ", reverse)
Faculty development program on “python”
Vikas college of arts, science & commerce Page 25
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla
reverse_number(1546)
Output
E. Write a function to check the input value is Armstrong and also write
the function for Palindrome.
Code:
# Python program to check if the number provided by the user is an
Armstrong number or not
def armstrong(num):
sum=0
# find the sum of the cube of each
digit temp = num
while temp > 0:
digit = temp %
10 sum += digit
** 3 temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
def palindrome(num):
n = num
rev = 0
while num != 0:
rev = rev * 10
rev = rev + int(num%10)
num = int(num / 10)
if n == rev:
print(n,"is palindrome number")
else:
print(n,"is not a palin")
Output
def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_factorial(n-1)
Output
Practical No.2
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)
Code:
def len_s(s):
count=0
for i in s:
if i != ' ':
count+=1
print('The total length of the string:',count)
s='God is great'
len_s(s)
Output:
Code:
def histogram(inputList):
for i in range(len(inputList)):
print (inputList[i]*'*')
List = [4,9,7]
histogram(List)
The code and the corresponding output is shown in the following screen shot.
Practical No.-3
Faculty development program on “python”
Vikas college of arts, science & commerce Page 33
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla
Code:
Output
B. 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:
Practical No.4
Write the program for the following: (by using list)
A. Write a program that takes two lists and returns true if they have at
least one common member.
Code:
l1=[1,2,3,4,5,6,]
l2=[11,12,13,14,15,6]
for i in l1:
for j in l2:
if i==j:
print ('The 2 list have at least one common element')
Output
Code:
#print list after removing the 0th, 2nd, 4th and 5th elements.
l1=[1,2,3,4,5,6,7,8,9,0]
print("Original List is",l1)
print("According to question we have to remove 0th->1,2nd->3,4th->5,5th-
>6") l1.remove(l1[0]) #this line will remove 1 from the list, Therefore l1[0]=2
print("After Removal of 0th element Now List is",l1)
print("Now we have to remove 3 from list which is at 1th position of index")
l1.remove(l1[1])
print("After Removal of 1st element of New List (original 2nd index element)
is",l1)
print("Now we have to remove 5 from list which is at 2nd position of index")
l1.remove(l1[2])
print("After Removal of 3rd element of New List (original 4th index element)
is",l1)
print("Now we have to remove 6 from list which is at 2nd position of index")
l1.remove(l1[2])
print (l1)
Output
Output
Python code :
l1=[2, 4, 7, 8, 9, 0]
print ("Original List is", l1)
l2=l1
print ("Clone List is ",l2)
Output
Practical No.5
Write the program for the following: (by using Dictionary)
Code:
Output:
Output:
Output:
Practical No.6
Output
B. Write a Python program to append text to a file and display the text.
Step:
1. First we have to create a sample .txt file in current directory where we save our
program code.
text.txt
What is Python language?
Python is a widely used high-level, general-purpose, interpreted,
dynamic programming language.
Its design philosophy emphasizes code readability, and its syntax
allows programmers to express concepts in fewer lines of code than
possible in languages such as C++ or Java.
Python supports multiple programming paradigms, including object-oriented,
imperative and functional programming or procedural styles.
It features a dynamic type system and automatic memory management and has a
large and comprehensive standard library.
The best way we learn anything is by practice and exercise questions. We
have started this section for those (beginner to intermediate) who are familiar
with Python.
Code:
def main():
f=open("text.txt","a+")
f.write("Welcome to Workshop on Python")
f.close()
if __name__=="__main__":
main()
Output:
Code Explaination:-
1. In Line 1 is used to define a function by using def keyword.
2. In Line 2 we open a file in append mode by using inbuilt method of file is open
( ) and mode a+
3. In Line 3 writing a line by using inbuilt method write() this written line is
added in last line of the file.
th
4. 4 Line contain close() method of a file for closing the opened file.
5. Line 5 contain __name__==”__main__”. Here __name__ variable is use for
calling the main method i.e. starting point of program execution like in C++ and
java main method.
6. if __name__ == "__main__": is used to execute some code only if the file
was run directly, and not imported.
Code:
'''
Write a Python program to read last n lines of a file.
'''
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())
if len(data) >= lines or f.tell() == 0:
print(''.join(data[-lines:]))
break
file_read_from_tail('text.txt',2)
Output:
Practical No.-7
Write the program for the following: (class and objects)
A. Design a class that store the information of student and display the same
class Student:
def _init_(self,name, sex,course,result):
self.name=name
self.sex=sex
self.course=course
self.result=result
def display(self, name, sex, course, result):
self.name=name
self.sex=sex
self.course=course
self.result=result
print ('Name:', name)
print ('Sex:',sex)
print ('course:',course)
print ('result:', result)
s1=Student()
s1.display(„Ashwin Mehta‟,‟M‟,‟B. Sc.(IT)‟,‟96.8%‟)
Output:
Code:
class Shape:
author= 'Ashwin Mehta'
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 ('Area of a rectangle',a)
print (author)
class Square(Shape): #class Square inherits class 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:
C. 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).
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.
Code:
class Numbers(object):
MULTIPLIER = 3.5
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
@classmethod
def multiply(cls, a):
return cls.MULTIPLIER * a
@staticmethod
def subtract(b, c):
return b - c
@property
def value(self):
return (self.x, self.y)
@value.setter
def value(self, xy_tuple):
Faculty development program on “python”
Vikas college of arts, science & commerce Page 49
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla
self.x=x
self.y=y
self.x, self.y = xy_tuple
@value.deleter
def value(self):
self.x=x
self.y=y
del self.x
del self.y
Output:
Practical No.-8
8. Write the program for the following: (IDLE and exception handling)
A. 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: import geometry 16 Try and add print
dir(geometry) to the file and run it. Now write a function
pointyShapeVolume(x, y, squareBase) that calculates the volume of a square
pyramid if squareBase is True and of a right circular cone if squareBase is
False. x is the length of an edge on a square if squareBase is True and the
radius of a circle when squareBase is False. y is the height of the object. First
use squareBase to distinguish the cases. Use the circleArea and squareArea
from the geometry module to calculate the base areas.
Code:-
import geometry
def pointyShapeVolume(x, h, square):
if square:
base = geometry.squareArea(x)
else:
base = geometry.circleArea(x)
return h * base / 3.0
print dir(geometry)
print pointyShapeVolume(4, 2.6, True)
print pointyShapeVolume(4, 2.6, False)
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)
Output:
Practical No.9
Write the program for the following: (Widget - GUI)
Code:
import Tkinter
from Tkinter import *
root=Tk()
O=Canvas(root,bg="red",width=500,height=500)
O.pack()
n = Label(root,text="Hello World")
n.pack()
root.mainloop()
OutPut:-
B. Try to change the widget type and configuration options to experiment with
other widget types like Message, Button, Entry, Checkbutton, Radiobutton,
Scale etc.
Code:
Message.py
#Message in Python
import tkinter
from tkinter import *
root = Tk()
var = StringVar()
label = Message( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()
Output:-
Button.py
Code:-
#Button in Python
import tkinter
from tkinter import *
top = tkinter.Tk()
def helloCallBack():
tkinter.messagebox.showinfo( "Hello Python", "Hello World")
B = tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
Output:
Entry.py
Code:
#Entry in Python
from tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
Output:-
CheckButton.py
#CheckButton In Python
import tkinter
from tkinter import *
top = Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C1.pack()
C2.pack()
top.mainloop()
Output:-
RadioButton.py
Code:
#RadioButton in Python
import tkinter
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var,
value=1, command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text="Option 2", variable=var, value=2,
Faculty development program on “python”
Vikas college of arts, science & commerce Page 58
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla
command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text="Option 3", variable=var,
value=3, command=sel)
R3.pack( anchor = W)
label = Label(root)
label.pack()
root.mainloop()
Output:
Scale.py
Code:-
#Scale in Python
from tkinter import *
def sel():
selection = "Value = " + str(var.get())
label.config(text = selection)
root = Tk()
var = DoubleVar()
scale = Scale( root, variable = var )
scale.pack(anchor=CENTER)
button = Button(root, text="Get Scale Value", command=sel)
button.pack(anchor=CENTER)
label = Label(root)
label.pack()
root.mainloop()
Output:-
Practical No.10
Design the database applications for the following: (Refer database Chapter)
Code:
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n
it')
# prepare a cursor object using cursor()
method cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
print("Table Created Successfully");
# disconnect from server
db.close()
Code:-
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='p
ython_mysql')
# prepare a cursor object using cursor()
method cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Nitesh', 'Shukla', 23, 'M', 20000)"""
try:
# Execute the SQL command
cursor.execute(sql)
print ("Data Inserted Successfully...!")
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Code:
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n
it')
# prepare a cursor object using cursor()
method cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
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]
# Now print fetched result
print ("Fname=%s,Lname=%s,Age=%d,Sex=%s,Income=%d" % \
(fname, lname, age, sex, income ))
except:
print ("Error: unable to fecth data")
# disconnect from server
db.close()
DataAdd.py
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n
it')
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Ashwin', 'Mehta', 23, 'M', 22000)
try:
# Execute the SQL command
cursor.execute(sql)
print("Data Added Successfully")
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Delete.py
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n
it')
# prepare a cursor object using cursor() method
Faculty development program on “python”
Vikas college of arts, science & commerce Page 67
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla
cursor = db.cursor()
# Prepare SQL query to UPDATE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE < '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
print "Data Deleted SuccessFully..!"
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Update.py
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n
it')
# 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:
# Execute the SQL command
cursor.execute(sql)
print ("Data Deleted SuccessFully..!")
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()