Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # for inserting items in database
- from tkinter import *
- #import mysql.connector as mysql
- import pymysql
- def insertcall():
- conn=pymysql.connect(user='root',password='root',host='localhost',db='temp')
- cursor=conn.cursor()
- # cursor.execute("Use temp")
- sql="insert into emp1 values('"+fname.get()+"','"+lname.get()+"',"+age.get()+","+income.get()+")"
- cursor.execute(sql)
- conn.commit()
- win=Tk()
- win.title("Employee Details")
- Label(win,text="First Name").grid(row=0,column=0)
- Label(win,text="Last Name").grid(row=1,column=0)
- Label(win,text="Age").grid(row=2,column=0)
- Label(win,text="Income").grid(row=3,column=0)
- fname=Entry(win)
- lname=Entry(win)
- age=Entry(win)
- income=Entry(win)
- fname.grid(row=0,column=1)
- lname.grid(row=1,column=1)
- age.grid(row=2,column=1)
- income.grid(row=3,column=1)
- b1=Button(win,text='Quit',command=win.destroy)
- b1.grid(row=4,column=0,sticky=W,pady=4)
- b2=Button(win,text='Insert',command=insertcall)
- b2.grid(row=4,column=1,sticky=W,pady=4)
- mainloop()
- #Program to show data from database
- from tkinter import *
- from tkinter import messagebox
- #import mysql.connector as mysql
- import pymysql
- def showLastInfo():
- conn=pymysql.connect(user='root',password='root',host='127.0.0.1')
- cursor=conn.cursor()
- cursor.execute("use temp")
- sql="SELECT * FROM emp1"
- cursor.execute(sql)
- results=cursor.fetchall()
- for row in results:
- fn=row[0]
- ln=row[1]
- age=row[2]
- inc=row[3]
- #Display last Inserted information in message box
- messagebox.showinfo(title='Last Info',message="First Name:"+fn+"\nLast Name:"+ln+"\nAge:"+str(age)+"\nIncome:"+str(inc))
- conn.comit()
- win=Tk()
- win.title("Check Inserted data")
- B1=Button(win,text='Check Inserted Info',command=showLastInfo)
- B1.pack()
- mainloop()
- #updating information in database
- from tkinter import *
- from tkinter import messagebox
- import pymysql
- #creating connection object and selecting current database to use.
- conn=pymysql.connect(user='root',password='root',host='localhost',db='temp')
- cursor=conn.cursor()
- def callvalues():
- lname.config(state=NORMAL)
- age.config(state=NORMAL)
- income.config(state=NORMAL)
- cursor.execute("Use temp")
- sql="SELECT * FROM emp1 WHERE fNAME='"+fname.get()+"'"
- cursor.execute(sql)
- results=cursor.fetchall()
- print(results)
- for row in results:
- dbfname=row[0]
- dblname=row[1]
- dbage=row[2]
- dbincome=row[3]
- lname.insert(0,dblname)
- age.insert(0,dbage)
- income.insert(0,dbincome)
- conn.commit()
- def updatecall():
- cursor.execute("USE temp")
- sql="UPDATE emp1 SET lname='"+lname.get()+"',age="+age.get()+",income="+income.get()+" WHERE fname='"+fname.get()+"'"
- cursor.execute(sql)
- conn.commit()
- messagebox.showinfo(title='Last Info',message="Information Updated")
- win=Tk()
- Label(win,text=" Enter First Name").grid(row=0)
- fname=Entry(win)
- fname.grid(row=0,column=1)
- b1=Button(win,text='Click here to get values',command=callvalues)
- b1.grid(row=1,sticky=N,pady=4,columnspan=2)
- Label(win,text="Last Name").grid(row=2)
- Label(win,text="Age").grid(row=3)
- Label(win,text="Income").grid(row=4)
- lname=Entry(win,state=DISABLED)
- lname.grid(row=2,column=1)
- age=Entry(win,state=DISABLED)
- age.grid(row=3,column=1)
- income=Entry(win,state=DISABLED)
- income.grid(row=4,column=1)
- b2=Button(win,text='Update',command=updatecall)
- b2.grid(row=5,columnspan=2,sticky=N,pady=4)
- mainloop()
- # deleting and modyfying information in database::
- from tkinter import *
- from tkinter import messagebox
- import pymysql
- #creating connection object and selecting current database to use.
- conn=pymysql.connect(user='root',password='root',host='localhost',db='temp')
- cursor=conn.cursor()
- def deletecall():
- cursor.execute("Use temp")
- sql="DELETE FROM emp1 WHERE fNAME='"+fname.get()+"'"
- cursor.execute(sql)
- print(sql)
- cursor.execute(sql)
- conn.commit()
- messagebox.showinfo(title='Conformation',message="Information Deleted")
- def checkcall():
- cursor.execute("USE temp")
- sql="SELECT * FROM emp1 WHERE fNAME='"+fname.get()+"'"
- cursor.execute(sql)
- #IF no recordset return for INSERT,UPDATE,CREATE,etc
- if cursor.description is None:
- conn.commit()
- else:
- messagebox.showinfo(title='Last Info',message="No record found")
- win=Tk()
- Label(win,text=" Enter First Name").grid(row=0)
- fname=Entry(win)
- fname.grid(row=0,column=1)
- b1=Button(win,text='Delete values',command=deletecall)
- b1.grid(row=1,sticky=N,pady=4,column=0)
- b1=Button(win,text='check',command=checkcall)
- b1.grid(row=1,sticky=N,pady=4,column=1)
- mainloop()
- from tkinter import *
- from tkinter import messagebox
- import pymysql
- #creating connection object and selecting current database to use.
- conn=pymysql.connect(user='root',password='root',host='localhost',db='temp')
- cursor=conn.cursor()
- def deletecall():
- cursor.execute("Use temp")
- sql="DELETE FROM emp1 WHERE fNAME='"+fname.get()+"'"
- cursor.execute(sql)
- print(sql)
- cursor.execute(sql)
- conn.commit()
- messagebox.showinfo(title='Conformation',message="Information Deleted")
- def checkcall():
- cursor.execute("USE temp")
- sql="SELECT * FROM emp1 WHERE fNAME='"+fname.get()+"'"
- cursor.execute(sql)
- #IF no recordset return for INSERT,UPDATE,CREATE,etc
- if cursor.description is None:
- conn.commit()
- else:
- messagebox.showinfo(title='Last Info',message="No record found")
- win=Tk()
- Label(win,text=" Enter First Name").grid(row=0)
- fname=Entry(win)
- fname.grid(row=0,column=1)
- b1=Button(win,text='Delete values',command=deletecall)
- b1.grid(row=1,sticky=N,pady=4,column=0)
- b1=Button(win,text='check',command=checkcall)
- b1.grid(row=1,sticky=N,pady=4,column=1)
- mainloop()
- 5.a. Write a Python script to sort (ascending and descending) a dictionary by value.
- import operator
- x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
- sorted_x = sorted(x.items(), key=operator.itemgetter(1))
- print(sorted_x)
- sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
- print(sorted_x)
- 1. Write the program for the following:......................................................................
- 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.
- from datetime import datetime
- name = input("What's your name?\n")
- age = int(input("How old are you?\n"))
- hundred = int((100-age)+datetime.now().year)
- print("Hi, %s. You are %s year old and you will turn 100
- year old in %s." %(name,age,hundred))
- 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.
- num=int(input("Enter the Number?\n"))
- if num%2==0:
- print ("Number is Even.")
- else:
- print ("Number is Odd.")
- c. Write a program to generate the Fibonacci series.
- v = int (input("Enter the range number:\n"))
- a=0
- b=1
- for n in range(0,v):
- if(n<=1):
- c=n
- else:
- c=a+b
- a=b
- b=c
- print(c)
- d. Write a function that reverses the user defined value.
- def revnum(num):
- reverse=0
- while num!=0:
- rem=num%10
- reverse=rem+reverse*10
- num=num//10
- print("Reverse Number:%d"%reverse)
- num=int(input("Enter any Number:"))
- revnum(num)
- e. Write a function to check the input value is Armstrong and also write the
- function for Palindrome.
- def armnum(num):
- sum=0
- temp=num
- while temp>0:
- digit=temp%10
- sum=sum+digit**3
- temp=temp//10
- if num==sum:
- print(num,"is a Armstrong Number.")
- else:
- print(num,"is not an Armstrong Number.")
- def palnum(num):
- sum=0
- temp=num
- while num!=0:
- rem=num%10
- sum=rem+sum*10
- num=num//10
- if temp==sum:
- print(temp,"is a palindrome Number.")
- else:
- print(temp,"is not a palindrome Number.")
- num=int(input("Enter any Number:"))
- armnum(num)
- palnum(num)
- f. Write a recursive function to print the factorial for a given number.
- def fact(x):
- if x==1:
- return 1
- else:
- return (x*fact(x-1))
- num=int(input("Enter any Number:\n"))
- print("The Factorial of",num,"is",fact(num))
- 2. Write the program for the following:
- 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.
- def vowel(ch):
- if(ch=="A" or ch=="a" or ch=="E" or ch=="e" or
- ch=="I" or ch=="i" or ch=="O" or ch=="o" or ch=="U" or
- ch=="u"):
- print(ch,"is a Vowel.")
- else:
- print(ch,"is not a Vowel.")
- ch=input("Enter any Character:")
- vowel(ch)
- b. Define a function that computes the length of a given list or string.
- def complen(s):
- count=0
- for i in s:
- count=count+1
- return count
- print(complen([5,4,6,9,7,8,7]))
- print(complen('Santosh'))
- 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:
- ****
- *********
- *******
- def histogram(items):
- for n in items:
- output=''
- times=n
- while(times>0):
- output=output+'*'
- times=times-1
- print(output)
- histogram([4,9,15])
- 3. Write the program for the following:
- 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.
- import string, sys
- def ispangram(str1, alphabet=string.ascii_lowercase):
- alphaset = set(alphabet)
- return alphaset <= set(str1.lower())
- print(ispangram('The quick brown fox jumps over the lazy
- dog'))
- 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.
- a=[1,1,2,3,5,8,13,21,34,55,89]
- for i in a:
- if i<5:
- print(i)
- 4. Write the program for the following:
- a Write a program that takes two lists and returns True if they have at least
- one common member.
- def common_data(list1, list2):
- result = False
- for x in list1:
- for y in list2:
- if x == y:
- result = True
- return result
- print(common_data([1, 2, 3, 4, 5], [5, 6, 7, 8, 9]))
- print(common_data([1, 2, 3, 4, 5], [6, 7, 8, 9]))
- b. Write a Python program to print a specified list after removing the 0th,
- 2nd, 4th and 5th elements.
- name = ['Name1','Name2','Name3','Name4','Name5','Name6','Name7']
- name = [x for (i,x) in enumerate(name) if i not in
- (0,2,4,5)]
- print(name)
- c. Write a Python program to clone or copy a list
- original_list = [10, 22, 44, 23, 4]
- new_list = list(original_list)
- print(original_list)
- print(new_list)
- 5. Write the program for the following:
- a. Write a Python script to sort (ascending and descending) a dictionary by
- value.
- import operator
- d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
- print('Original dictionary : ',d)
- sorted_d = sorted(d.items(), key=operator.itemgetter(0))
- print('Dictionary in ascending order by value :
- ',sorted_d)
- sorted_d = sorted(d.items(),
- key=operator.itemgetter(0),reverse=True)
- print('Dictionary in descending order by value :
- ',sorted_d)
- 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}
- 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)
- c. Write a Python program to sum all the items in a dictionary.
- my_dict = {'data1':100,'data2':-54,'data3':247}
- print(my_dict)
- print(sum(my_dict.values()))
- 6. Write the program for the following:
- a. Write a Python program to read an entire text file.
- Python.txt
- Python is a widely used high-level programming language
- for general-purpose programming,
- created by Guido van Rossum and first released in 1991.
- Python interpreters are available for many operating
- systems, allowing Python code to run on a wide variety of
- systems.
- Code:
- f=open('Python.txt','r')
- t=f.read()
- print(t)
- f.close()
- b. Write a Python program to append text to a file and display the text.
- f=open('Python.txt','a+')
- f.write('Python Programming Practical.\n')
- f=open('Python.txt','r')
- t=f.read()
- print(t)
- f.close()
- c. Write a Python program to read last n lines of a file.
- f=open('Python.txt','r')
- t=f.readlines()
- print(t[-1])
- f.close()
- 7. Write the program for the following:
- a. Design a class that store the information of student and display the
- same
- class student:
- def info(self,studname, studaddr):
- print("Name:",studname,"\nAddress:",studaddr)
- obj = student()
- obj.info('Santosh','Mumbai')
- b. Implement the concept of inheritance using python
- class st:
- def s1(self):
- print('Base Class')
- class st1(st):
- def s2(self):
- print('Derived Class')
- t=st1()
- t.s1()
- t.s2()
- 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.
- class Numbers:
- MULTIPLIER = 3
- def __init__(self, x, y):
- self.x = x
- self.y = y
- def add(self):
- 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):
- self.x, self.y = xy_tuple
- @value.deleter
- def value(self):
- del self.x
- del self.y
- T=Numbers(2,4)
- print(T.add())
- print(T.multiply(2))
- print(Numbers.subtract(4,3))
- 8.
- a.
- Write the program for the following:
- 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
- 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.
- geometry.py
- import math
- def sphereArea(r):
- return 4*math.pi*r**2
- def sphereVolumne(r):
- return 4*math.pi*r**3/3
- def sphereMetrics(r):
- return sphereArea(r),sphereVolumne(r)
- def circleArea(r):
- return math.pi*r**2
- def squareArea(x):
- return x**2
- square.py
- 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))
- b. Write a program to implement exception handling.
- try:
- num=int(input('Enter Number:'))
- re=10/num
- except(ValueError, ZeroDivisionError):
- print('Something is Wrong.')
- else:
- print('Division is:',re)
- 9. Write the program for the following:
- a. Try to configure the widget with various options like: bg=”red”, family=”times”,
- size=18
- import tkinter as tk
- win=tk.Tk()
- win.title('Practical')
- def redclick():
- label.config(text='Helvetica Font')
- label.config(bg='red')
- label.config(font=('Helvetica',16))
- def greenclick():
- label.config(text='Cambria Font')
- label.config(bg='green')
- label.config(font=('Cambria',18))
- def yellowclick():
- label.config(text='Arial Font')
- label.config(bg='yellow')
- label.config(font=('Calbari',14))
- label=tk.Label(win,text="Python Practical",bg='white')
- label.pack()
- B1=tk.Button(win,text='Red
- Click',relief='raised',command=redclick)
- B1.pack(side='left')
- B2=tk.Button(win,text='Green
- Click',relief='raised',command=greenclick)
- B2.pack(side='left')
- B3=tk.Button(win,text='Yellow
- Click',relief='raised',command=yellowclick)
- B3.pack(side='left')
- win.mainloop()
- b.
- Try to change the widget type and configuration options to experiment with other
- widget types like Message, Button, Entry, Checkbutton, Radiobutton, Scale etc.
- from tkinter import *
- def swap():
- if v.get():
- e.pack_forget()
- mb.pack(anchor='w',side='right')
- l2.config(text='Use Menu Below.')
- l2.config(bg='yellow')
- l2.config(font=('Helvetica',16,'italic'))
- else:
- mb.pack_forget()
- e.pack(anchor='w',side='left')
- l2.config(text='Use Entry Box Below.')
- l2.config(bg='Green')
- l2.config(font=('Cambria', 16, 'bold'))
- e.focus()
- t=Tk()
- v=IntVar(t)
- c=Checkbutton(t,command=swap,text='Select to use
- menu.',variable=v)
- c.pack(anchor='w')
- f1=Frame(t)
- l1=Label(f1,text='Select the Menu item of your choice:')
- l1.pack(side='left')
- l2=Label(f1,text='Use Entry Box
- Below.',bg='green',font=('Cambria',16,'bold'))
- l2.pack(side='top')
- f=Frame(f1)
- f.pack(side='left')
- e=Entry(f,width=35)
- mb=Menubutton(f,width=25,text='Veg',indicatoron=1,relief='sun
- ken',anchor='w')
- m=Menu(mb,tearoff=0);mb.configure(menu=m)
- for s in 'Veg nonVeg Chinese French'.split():
- m.add_command(label=s,command=lambda s=s:
- mb.configure(text=s))
- f.pack()
- f1.pack()
- swap()
- b=Button(t,text='Place Order',relief='raised',
- fg='red',command=t.destroy);
- b.pack(side='top')
- f.mainloop()
- 1. 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.
- name = input("Enter name : ")
- age = int(input("Enter age : "))
- yrdiff = 2017 + (100 - age)
- print("You will be turn to 100 in ", yrdiff, " year")
- Output:
- Enter name : Ravi
- Enter age : 30
- You will be turn to 100 in 2087 year
- 1. 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.
- no = int(input("Enter number : "))
- if no % 2 == 0:
- print("Number is Even")
- else:
- print("Number is Odd")
- 1. c. Write a program to generate the Fibonacci series.
- def fibo(n):
- if n == 0:
- return 0
- elif n == 1:
- return 1
- else:
- return fibo(n-1) + fibo(n-2)
- #main
- n = int(input("Enter number : "))
- print("Fibonacci series : ")
- for i in range(n+1):
- print(fibo(i), " ", end = '')
- 2. c. Define a procedure histogram() that takes a list, for example, histogram([4, 9, 7]) and print: **** ********* *******
- def histogram(list):
- for n in list:
- print(n * '*')
- #main
- histogram([4, 8, 9, 3])
- 4. b. Write a Python program to print a specified list after removing the 0th, 2nd, 4th and 5th elements.
- list1 = [10, 0, 3, 5, -100, 87, 65]
- print(list1)
- del list1[5]
- del list1[4]
- del list1[2]
- del list1[0]
- print(list1)
- 5. c. Write a Python program to sum all the items in a dictionary.
- dict1 = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
- listofvalues = dict1.values()
- sum = 0
- for n in listofvalues:
- sum += n
- print("Sum = ", sum)
Add Comment
Please, Sign In to add comment