Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 70
At a glance
Powered by AI
The document discusses the steps to install Python and MySQL and how to perform basic CRUD (create, read, update, delete) operations on a database using Python scripts.

The steps to install Python 3.4.x and MySQL Server 5.1 are discussed on pages 2-10. This includes downloading and installing both applications as well as configuring MySQL connectivity in Python.

The document shows examples of Python scripts (DataAdd.py, Delete.py, Update.py) that allow adding a record (on page 66), deleting records that match a condition (on page 67-68), and updating records (implied but not shown).

Compiled By: Prof. Kiran Gurbani & Nitesh N.

Shukla

Vidya Vikas Education Society’s


Vikas College of Arts, Science & Commerce
Re-accredited “A” Grade by NAAC & ISO 9001:2008 Certified
Vikhroli-E,Mumbai-400083

Department of Information Technology & Computer Science In


Association With
University Department of Information Technology
University of Mumbai

TWO DAY’S FACULTY DEVELOPMENT


PROGRAM ON
“PYTHON”
(Revised Syllabus of S.Y.B.Sc.IT.)

Resource person
Prof.Kiran Gurbani
(HOD, IT & CS Department, RKT College of Arts, Science & Commerce)

Prof. Rajendra Patil


(Co-ordinator, S.K. Somaiya College of Arts, Science & Commerce)

Faculty development program on “pytHon”


Vikas college of arts, science & commerce Page 1
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

S.Y.BSc.IT
SEMESTER-III
PYTHON PROGRAMMING
PRACTICAL
MANUAL
2017-2018
Compiled By:
PROF. KIRAN GURBANI
&
PROF.NITESH N. SHUKLA

Faculty development program on “python”


Vikas college of arts, science & commerce Page 2
Compiled By: Prof. Kiran Gurbani & 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

Faculty development program on “python”


Vikas college of arts, science & commerce Page 3
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

4. Click Next

5. Click Yes if any prompt is coming then click Next

Faculty development program on “python”


Vikas college of arts, science & commerce Page 4
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

6.Click Finish

7. Now install MySQL


Installation of MySQL Server 5.1

1. To install MySQL Server 5.1

Faculty development program on “python”


Vikas college of arts, science & commerce Page 5
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

2. Click on Next Button

3. Click on Next Button

Faculty development program on “python”


Vikas college of arts, science & commerce Page 6
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

4. Click on Install Button

5. Click on Install Button

Faculty development program on “python”


Vikas college of arts, science & commerce Page 7
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

6. Click on Install Button

7. Click on Next Button

Faculty development program on “python”


Vikas college of arts, science & commerce Page 8
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

8. Click on Next Button

9. Click on Finish Button

Faculty development program on “python”


Vikas college of arts, science & commerce Page 9
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

10. Click on Next Button

11. Click on Next Button

Faculty development program on “python”


Vikas college of arts, science & commerce Page 10
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

12. Click on Next Button

13. Click on Next Button

Faculty development program on “python”


Vikas college of arts, science & commerce Page 11
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

14. Click on Next Button

15. Click on Next Button

Faculty development program on “python”


Vikas college of arts, science & commerce Page 12
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

16. Click on Next Button

17. Click on Next Button

18. Select First CheckBox and click on Next

Faculty development program on “python”


Vikas college of arts, science & commerce Page 13
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

19. Enter password–“ password” It will be used in database connection and click on Next button

20. Click on execute button

Faculty development program on “python”


Vikas college of arts, science & commerce Page 14
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

21. Click on Finish Button

Faculty development program on “python”


Vikas college of arts, science & commerce Page 15
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Now Install Mysql Connector for Python 3.4. Click on the Following
Windows Installer File.

8. Now Copy the Following file in Python Directory.

Faculty development program on “python”


Vikas college of arts, science & commerce Page 16
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

9. Now Double Click on this Application and follow the step.

Faculty development program on “python”


Vikas college of arts, science & commerce Page 17
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Faculty development program on “python”


Vikas college of arts, science & commerce Page 18
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Faculty development program on “python”


Vikas college of arts, science & commerce Page 19
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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()

Faculty development program on “python”


Vikas college of arts, science & commerce Page 20
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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

Faculty development program on “python”


Vikas college of arts, science & commerce Page 21
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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 :

# Python program to check if the input number is odd or even.


# A number is even if division by 2 give a remainder of 0.
# If remainder is 1, it is odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Python Code :-

Output:-

Faculty development program on “python”


Vikas college of arts, science & commerce Page 22
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

C. Write a program to generate the Fibonacci series.

Code:

# Program to display the Fibonacci sequence up to n-th term where n is provided


by the user
# change this value for a different result
nterms = 10

# uncomment to take input from the user


#nterms = int(input("How many terms? "))

# first two terms


n1 = 0
n2 = 1
count = 2

# check if the number of terms is


valid if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
print(n1,",",n2,end=', ')

Faculty development program on “python”


Vikas college of arts, science & commerce Page 23
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

while count < nterms:


nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1

Faculty development program on “python”


Vikas college of arts, science & commerce Page 24
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Output

Fibonacci series by using function

D. Write a function that reverses the user defined value.

# Python Program to Reverse a Number using While loop by using function

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

Same Program on Python2.7 on Command prompt

Faculty development program on “python”


Vikas college of arts, science & commerce Page 26
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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")

# take input from the user


num = int(input("Enter a number to chk it is armstrong or not: "))
armstrong(num)
# take input from the user
num = int(input("Enter a number to chk it is palindrome or not: "))
palindrome(num)

Faculty development program on “python”


Vikas college of arts, science & commerce Page 27
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Output

Faculty development program on “python”


Vikas college of arts, science & commerce Page 28
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

F. Write a recursive function to print the factorial for a given number.


# Python program to find the factorial of a number using recursion

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)

#take input from the user


num = int(input("Enter a number: "))

# check is the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative
numbers") elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))

Faculty development program on “python”


Vikas college of arts, science & commerce Page 29
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Output

Faculty development program on “python”


Vikas college of arts, science & commerce Page 30
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Practical No.2

Write the program for the following: ( by using functions)

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)

The code and the output is shown in the following screenshot.

Faculty development program on “python”


Vikas college of arts, science & commerce Page 31
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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
print('The total length of the string:',count)
s='God is great'
len_s(s)

Output:

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:
****
*******
** *
******

Faculty development program on “python”


Vikas college of arts, science & commerce Page 32
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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

Write the program for the following: (by using list)

A. 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:

import string, sys


if sys.version_info[0] < 3:
input = raw_input
def ispangram(sentence, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(sentence.lower())
print ( ispangram(input('Sentence: ')) )

Output

Faculty development program on “python”


Vikas college of arts, science & commerce Page 34
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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:

# Program to trim list list_trim.py


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)

Faculty development program on “python”


Vikas college of arts, science & commerce Page 35
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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

Faculty development program on “python”


Vikas college of arts, science & commerce Page 36
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

B. Write a Python program to print a specified list after removing the


0th, 2nd, 4th and 5th elements.

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)

Faculty development program on “python”


Vikas college of arts, science & commerce Page 37
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Output

You can try without print statements

Output

Faculty development program on “python”


Vikas college of arts, science & commerce Page 38
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

C. Write a Python program to clone or copy a list

Python code :

l1=[2, 4, 7, 8, 9, 0]
print ("Original List is", l1)
l2=l1
print ("Clone List is ",l2)

Output

Faculty development program on “python”


Vikas college of arts, science & commerce Page 39
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Practical No.5
Write the program for the following: (by using Dictionary)

A. Write a Python script to sort (ascending and descending) a dictionary by


value.

Code:

released={'Python 3.6': 2017,'Python 1.0': 2002, 'Python 2.3': 2010}


print('Original dictionary : ',released)
print('Dictionary in ascending order by Value : ')
for key,value in sorted(released.items()):
print (key,value)
print ('Dictionary in descending order by Value :')
for key,value in sorted(released.items(),reverse=True):
print (key,value)

Output:

Faculty development program on “python”


Vikas college of arts, science & commerce Page 40
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

B. 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}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)

Output:

C. Write a Python program to sum all the items in a dictionary.


Code:
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))

Output:

Faculty development program on “python”


Vikas college of arts, science & commerce Page 41
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Practical No.6

Write the program for the following: (File handling)


A. Write a Python program to read an entire text file.
Code:
'''
Write a Python program to read an entire text file.
'''
def file_read(fname):
txt = open(fname)
print(txt.read())
file_read('text.txt')

Output

Faculty development program on “python”


Vikas college of arts, science & commerce Page 42
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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()

Faculty development program on “python”


Vikas college of arts, science & commerce Page 43
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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.

C. Write a Python program to read last n lines of a file.

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

Faculty development program on “python”


Vikas college of arts, science & commerce Page 44
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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:

Faculty development program on “python”


Vikas college of arts, science & commerce Page 45
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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%‟)

Faculty development program on “python”


Vikas college of arts, science & commerce Page 46
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Output:

B. Implement the concept of inheritance using python

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)

Faculty development program on “python”


Vikas college of arts, science & commerce Page 47
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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

Faculty development program on “python”


Vikas college of arts, science & commerce Page 48
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

property, and write a setter and a deleter for manipulating the values of x
and y.

Points To Remember before going to excute the following code:


1. We have __init__, a typical initializer of Python class instances, which
receives arguments as a typical instancemethod, having the first non-
optional argument (self) that holds reference to a newly created instance.
2. A class method is a method that is bound to a class rather than its object.
It doesn't require creation of a class instance, much like staticmethod.
The difference between a static method and a class method is:
 Static method knows nothing about the class and just deals with the
 parameters
 Class method works with the class since its parameter is always the class
itself.
3. It is often considered best practice to create getters and setters for a class's
public properties. Many languages allow you to implement this in different
ways, either by using a function (like person.getName ()), or by using a
language-specific get or set construct. In Python, it is done using @property.

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:

Faculty development program on “python”


Vikas college of arts, science & commerce Page 50
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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)

Faculty development program on “python”


Vikas college of arts, science & commerce Page 51
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

B. Write a program to implement exception handling.

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)

Faculty development program on “python”


Vikas college of arts, science & commerce Page 52
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Output:

Faculty development program on “python”


Vikas college of arts, science & commerce Page 53
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Practical No.9
Write the program for the following: (Widget - GUI)

A. Try to configure the widget with various options like:


bg=”red”, family=”times”, size=18

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:-

Faculty development program on “python”


Vikas college of arts, science & commerce Page 54
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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 *

Faculty development program on “python”


Vikas college of arts, science & commerce Page 55
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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()

Faculty development program on “python”


Vikas college of arts, science & commerce Page 56
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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()

Faculty development program on “python”


Vikas college of arts, science & commerce Page 57
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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())

Faculty development program on “python”


Vikas college of arts, science & commerce Page 59
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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:-

Faculty development program on “python”


Vikas college of arts, science & commerce Page 60
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Practical No.10
Design the database applications for the following: (Refer database Chapter)

A. 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')
# 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()

Faculty development program on “python”


Vikas college of arts, science & commerce Page 61
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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)"""

Faculty development program on “python”


Vikas college of arts, science & commerce Page 62
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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()

Faculty development program on “python”


Vikas college of arts, science & commerce Page 63
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

B. 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')
# 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()

Faculty development program on “python”


Vikas college of arts, science & commerce Page 64
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Faculty development program on “python”


Vikas college of arts, science & commerce Page 65
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

C. Design a database application to that allows the user to add, delete


and modify the records.

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()

Faculty development program on “python”


Vikas college of arts, science & commerce Page 66
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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()

Faculty development program on “python”


Vikas college of arts, science & commerce Page 68
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

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()

Faculty development program on “python”


Vikas college of arts, science & commerce Page 69
Compiled By: Prof. Kiran Gurbani & Nitesh N. Shukla

Faculty development program on “python”


Vikas college of arts, science & commerce Page 70

You might also like