Python All
Python All
Python All
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:
hundred=int((100-age)+datetime.now().year)
print('Hello %s. you are %s year old. You will turn 100 years old in %s.'%(name,age,hundred))
Output :
>>>
sanket
24
Hello sanket. you are 24 year old. You will turn 100 years old in 2094.
>>>
Pract 1b
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 :
mod=num%2
if mod>0:
else:
Output :
>>>
Part 2
Code :
if(num%2)==0:
print("{0} is even".format(num))
else:
print("{0} is odd".format(num))
Output :
>>>
50 is even
>>>
Pract 1C
n1=0
n2=1
count=2
if nterms<=0:
elif nterms==1:
print(n1)
else:
print(n1,',',n2,end=',')
while count<nterms:
nth=n1+n2
print(nth,end=',')
n1=n2
n2=nth
count+=1
Output :
>>>
0 , 1,1,2,3,
>>>
Pract 1D
Reverse=0
while(Number>0):
Reminder=Number%10
Reverse=(Reverse*10)+Reminder
Number=Number//10
Output :
>>>
>>>
Part 2
Code :
def Reverse_Integer(Number):
Reverse=0
while(Number>0):
Reminder=Number%10
Reverse=(Reverse*10)+Reminder
Number=Number//10
return Reverse
Reverse=Reverse_Integer(Number)
Output :
>>>
>>>
Pract 1e
Aim: Write a function to check the input value is Armstrong and also write the function for
Palindrome
Program 2=
Code :
num=int(input("Enter a Number"))
sum1=0
n=num
while num!=0:
rem=num%10
sum1=sum1*10+rem
num=num//10
if sum1==n:
print(n,"is pallindrome")
else:
Output :
>>>
Enter a Number555
Pract 1e
Program 2
Code :
num=int(input("enter a number"))
sum=0
temp=num
while temp>0:
digit=temp%10
sum=sum+digit**3
temp=temp//10
if num==sum:
else:
>>>
enter a number153
>>>
>>>
enter a number151
>>>
Pract 1f
Aim: Write a recursive function to print the factorial for a given number
Code :
def recur_factorial(n):
if n==1:
return n
else:
return n*recur_factorial(n-1)
num=int(input("enter a number"))
if num<=0:
elif num==0:
print("Factorial of 0 is 1")
else:
Output :
>>>
enter a number5
>>>
>>>
enter a number0
Factorial of 0 is 1
>>>
>>>
enter a number-1
>>>
Pract 2a
Aim: 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 is_vowels(char):
vowels=('a','e','i','o','u')
if char in vowels:
return True
return False
c=input("enter a char\n")
print(is_vowels(c))
Output :
>>>
enter a char
True
>>>
enter a char
False
>>>
Pract 2b
Aim: Define a function that computes the length of a given list or string.
Code:
def length(string):
count=0
for i in string:
count+=1
return count
s=input("enter a string")
print("length is",length(s))
Output :
"""
>>>
length is 7
>>>
"""
Pract 2c
def histogram(inputlist):
for i in range(len(inputlist)):
print(inputlist[i]*'*')
list=[2,4,3,5]
histogram(list)
Output
>>>
**
****
***
*****
>>>
Pract 3a
Code :
def panagram(nt):
check="abcdefghijklmnopqrstuvw"
for i in check:
if(i in nt):
continue
else:
return False
return True
if(panagram(n.lower())):
print("Yes it is a Panagram")
else:
output :
>>>
Enter Any Text:the quick brown fox jumps over the lazy dog
Yes it is a Panagram
>>>
>>>
No it is not a Panagram
Pract 3b
Code :
def lessThanfivechecker(li,n):
return new_li
li=[1,1,2,3,5,8,13,21,34,55,89]
n=int(input("Enter a number to return a list that contain only elements from the orignal list that are
smaller than that enter number:"))
new_li=lessThanfivechecker(li,n)
print(new_li)
Output:
>>>
Enter a number to return a list that contain only elements from the orignal list that are smaller than that
enter number:5
[1, 1, 2, 3]
>>>
"""
PRAC 4A
Aim:write a program that takes two list and returns true if they have atleast 1
common number
def common_data(list1,list2):
result=False
for x in list1:
for y in list2:
if x==y:
result=True
return result
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]))
PRAC 4B
Aim: Write a Python program to print a specified list after removing the 0th, 2nd,
4th and 5th elements.
color=['red','green','white','black','pink','yellow']
color1=[]
for(i,x)in enumerate (color):
if i in(0,4,5):
continue
color1.append(x)
print(color1)
PRAC 4B1
Aim: Write a Python program to print a specified list after removing the even num
from it.
num=[7,8,120,25,44,20,27]
num=[x for x in num if x%2!=0]
print (num)
PRAC 4C
Aim: 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:',original_list)
print('new list:',new_list)
PRAC 5A
Aim: Write a Python script to sort (ascending and descending) a dictionary by
value.
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)
PRAC5B
Aim: Write a Python script to concatenate following dictionaries to create a new
one.
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)
PRAC5C
Aim:
my_dict={'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
PRAC6A
Aim: Write a Python program to read an entire text file.
def file_read(fname):
txt=open(fname)
print(txt.read())
file_read('text.txt')
PRAC6B
Aim: Write a Python program to append text to a file and display the text
def file_read(fname):
from itertools import islice
with open(fname,"w")as myfile:
myfile.write("Python Exercises \n")
myfile.write("Java Exercises")
txt=open(fname)
print(txt.read())
file_read('abc.txt')
PRAC 6B1
Aim: Write a Python program to concantinate the text file.
def main():
f=open("text.txt","a+")
f.write("Good Morning")
f.close()
main()
Prac 7a
Aim:design a class that stores the information of student and display the same
import datetime
class Person:
def __init__(self,name,surname,birthdate,address,telephone,email):
self.name=name
self.birthdate=birthdate
self.surname=surname
self.address=address
self.telephone=telephone
self.email=email
def age(self):
today=datetime.date.today()
age=today.year-self.birthdate.year
if today<datetime.date(today.year,self.birthdate.month,self.birthdate.day):
age-=1
return age
person=Person("nitesh","shukla",datetime.date(1988,11,21),"virar","8200082097","nishi@gmail.com")
print(person.name)
print(person.surname)
print(person.age())
print(person.address)
print(person.telephone)
print(person.email)
PRAC 7B
class Person:
def __init__(self,first,last):
self.firstname=first
self.lastname=last
def Name(self):
return self.firstname+","+self.lastname
class Employee(Person):
def __init__(self,first,last,staffnum):
Person.__init__(self,first,last)
self.staffnumber=staffnum
def GetEmployee(self):
return self.Name()+","+self.staffnumber
x=Person("Nitesh","shukla")
y=Employee("brjesh","Shukla","1001")
print(x.Name())
print(y.GetEmployee())
Prac7b1
class Shape:
author='Ashwin Mehta'
def _init_(self,x,y):
self.x=x
self.y=y
def area1(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):
def _init_(self,x):
self.x=x
def area(self,x):
self.x=x
a=self.x*self.x
print('Area of square',a)
r=Shape()
r.area1(6,2)
s=Square()
s.area(5)
s.area1(8,5)
PRAC 7c
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
Code:-class numbers(object):
MULTIPLAYER=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.MULTIPLAYER*a
@staticmethod
def subtract(b,c):
return b-c
@property
def value(self):
print("getting value")
return(self.x,self.y)
@value.setter
def value(self,xy_tuple):
print("setting value")
self.x,self.y=xy_tuple
@value.deleter
def value(self):
print("deleting value")
del self.x
del self.y
print("value deleted")
x=numbers()
add=x.add(a,b)
print("addition is:",add)
sub=x.subtract(a,b)
print("subAtraction is:",sub)
mul=x.multiply(a)
print("multiplication is:",mul)
get_var=x.value
print(get_var)
x.value=(20,10)
get_var=x.value
print(get_var)
del x.value
9b
Aim:
Try to change the widget type and configuration options to experiment with other
widget types like Message, Button, Entry, Checkbutton, Radiobutton, Scale etc.
root=Tk()
f001=Label(root,text="GUI PROGRAMMING",font='times',fg='red')
f001.pack()
f002=Message(root,text="This is programm")
f002.pack()
Label(root,text="Name:",font='times').pack(anchor=W)
svalue=StringVar()
f003=Entry(root,textvariable=svalue)
f003.pack(anchor=W)
Label(root,text="Hobbies:",font='times').pack(anchor=W)
CheckVar1=IntVar()
CheckVar2=IntVar()
CheckVar3=IntVar()
C=Checkbutton(root,text="Music",variable=CheckVar1,onvalue=1,offvalue=0,width=20,height=2)
C.pack()
C=Checkbutton(root,text="Games",variable=CheckVar2,onvalue=1,offvalue=0,width=20,height=2)
C.pack()
C=Checkbutton(root,text="Dance",variable=CheckVar3,onvalue=1,offvalue=0,width=20,height=2)
C.pack()
Label(root,text="Gender",font='times').pack(anchor=W)
Radiovar=StringVar()
R1=Radiobutton(root,text="male",variable=Radiovar,value="male")
R1.pack(padx=5,pady=10,anchor=W)
R2=Radiobutton(root,text="female",variable=Radiovar,value="female")
R2.pack(padx=5,pady=15,anchor=W)
Label(root,text="Age",font='times').pack(anchor=W)
scalevar=IntVar()
scale=Scale(root,variable=scalevar,orient=HORIZONTAL)
scale.pack(anchor=W)
def function_when_passed():
choice=""
if(CheckVar1.get()==1):
choice=choice+"Music"
if(CheckVar2.get()==1):
choice=choice+"Games"
if(CheckVar3.get()==1):
choice=choice+"Dance"
"I am"+str(Radiovar.get())+
"age is"+str(scalevar.get())+
f005=Button(root,text="print",command=function_when_passed)
f005.pack()
root.mainloop()
pract 10
code: DEMO
import mysql.connector
db=mysql.connector.connect(host="localhost",port=3306,user="root",password="root",database
='test')
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
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");
db.commit()
db.close()
OUTPUT:
Pract 10 a)
Design simple database application that store and retrieve data
(first as per screen shots above create table as student with column as name
varchar(20),rollno varchar(20),marks varchar(20),sub varchar(20))
from tkinter import *
import mysql.connector
db=mysql.connector.connect(host="localhost",port=3306,user="root",password="root",database
='test')
cursor = db.cursor()
#insert function
def insert_method():
#rn=int(str(sroll.get()))
#print( type(rn))
def show_data():
sql="select * from student where name='"+sname.get()+"'"
cursor.execute(sql)
result=cursor.fetchall()
if not result:
messagebox.showinfo("no data","no such name in table")
else:
listbox=Listbox(win,width=50)
listbox.grid(row=4,columnspan=2)
for r in result:
listbox.insert(END,list(r))
db.commit()
win=Tk()
win.title("Search Data")
Label(win,text="enter student name to search").grid(row=0)
sname=Entry(win,width=20)
sname.grid(row=0,column=1)
b=Button(win,text="search",command=show_data).grid(row=3,columnspan=2)
mainloop()
OUTPUT:
Pract 10 c)
Design database application to delete and modify data
def show_data():
sql="select * from student where name='"+sname.get()+"'"
cursor.execute(sql)
result=cursor.fetchall()
if not result:
messagebox.showinfo("No data","no such name in table")
else:
for r in result:
stuname.insert(0,r[0])
sroll.insert(0,r[1])
smarks.insert(0,r[2])
ssub.insert(0,r[3])
db.commit()
def delete_data():
sql="delete from student where name='"+stuname.get()+"'"
cursor.execute(sql)
db.commit()
messagebox.showinfo("Information","selected row deleted")
stuname.delete(0,END)
sroll.delete(0,END)
smarks.delete(0,END)
ssub.delete(0,END)
def update_data():
sql="update student set
name='"+stuname.get()+"',rollno='"+sroll.get()+"',marks='"+smarks.get()+"',sub='"+ssub.get()+"'
where name='"+stuname.get()+"'"
cursor.execute(sql)
db.commit()
messagebox.showinfo("Information","selected row updated")
stuname.delete(0,END)
sroll.delete(0,END)
smarks.delete(0,END)
ssub.delete(0,END)
#search
win=Tk()
win.title("Search Data")
Label(win,text="enter student name to search").grid(row=0)
sname=Entry(win,width=20)
sname.grid(row=0,column=1)
b=Button(win,text="search",command=show_data).grid(row=3,columnspan=2)
#display in textbox
Label(win,text="Name").grid(row=5)
stuname=Entry(win,width=20)
stuname.grid(row=5,column=1)
Label(win,text="Roll No").grid(row=6)
sroll=Entry(win,width=20)
sroll.grid(row=6,column=1)
Label(win,text="Marks").grid(row=7)
smarks=Entry(win,width=20)
smarks.grid(row=7,column=1)
Label(win,text="Subject").grid(row=8)
ssub=Entry(win,width=20)
ssub.grid(row=8,column=1)
#delete & update button
b1=Button(win,text="Delete",command=delete_data).grid(row=9,column=1,columnspan=2)
b2=Button(win,text="Update",command=update_data).grid(row=9,column=0,columnspan=2)
mainloop()
db.close()
OUTPUT: