Sei sulla pagina 1di 43

Pract 1a

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:

from datetime import datetime

name=input('what is your name ?\n')

age=int(input('How old are you ?\n'))

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 :

>>>

what is your name ?

sanket

How old are you ?

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 :

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

mod=num%2

if mod>0:

print("this is an odd number.")

else:

print("this is an even number.")

Output :

>>>

Enter a number :20

this is an even number.

Part 2

Code :

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

if(num%2)==0:

print("{0} is even".format(num))

else:

print("{0} is odd".format(num))

Output :

>>>

Enter a number :50

50 is even

>>>
Pract 1C

Aim: Write a program to generate the Fibonacci series.


Code :

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

n1=0

n2=1

count=2

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=',')

while count<nterms:

nth=n1+n2

print(nth,end=',')

n1=n2

n2=nth

count+=1

Output :

>>>

How many terms ?5

fibonacci sequence upto 5 :

0 , 1,1,2,3,
>>>

Pract 1D

Aim: Write a function that reverses the user defined value.


Code :

Number=int(input("Please enter any number:"))

Reverse=0

while(Number>0):

Reminder=Number%10

Reverse=(Reverse*10)+Reminder

Number=Number//10

print("\n Reverse of entered number is=%d "%Reverse)

Output :

>>>

Please enter any number:5986

Reverse of entered number is=6

Reverse of entered number is=68

Reverse of entered number is=689

Reverse of entered number is=6895

>>>
Part 2

Code :

def Reverse_Integer(Number):

Reverse=0

while(Number>0):

Reminder=Number%10

Reverse=(Reverse*10)+Reminder

Number=Number//10

return Reverse

Number=int(input("Please Enter any Number:"))

Reverse=Reverse_Integer(Number)

print("\n Reverse of entered number is=%d "%Reverse)

Output :

>>>

Please Enter any Number:5698

Reverse of entered number is=8965

>>>

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:

print(n,"is not pallindrome")

Output :

>>>

Enter a Number555

555 is not pallindrome

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:

print(num,"is an Armstrong Number")

else:

print(num,"is an not Armstrong Number")


Output

>>>

enter a number153

153 is an Armstrong Number

>>>

>>> ================================ RESTART ================================

>>>

enter a number151

151 is an not Armstrong Number

>>>

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:

print("Sorry, Factorial is does not exist for negative number")

elif num==0:

print("Factorial of 0 is 1")
else:

print("The Factorial of",num,"is",recur_factorial(num))

Output :

>>>

enter a number5

The Factorial of 5 is 120

>>>

>>> ================================ RESTART ================================

>>>

enter a number0

Factorial of 0 is 1

>>>

>>> ================================ RESTART ================================

>>>

enter a number-1

Sorry, Factorial is does not exist for negative number

>>>

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

>>> ================================ RESTART ================================

>>>

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 :

"""

>>>

enter a stringhi guys

length is 7

>>>

"""

Pract 2c

Aim: Define a procedure histogram()


Code:

def histogram(inputlist):

for i in range(len(inputlist)):

print(inputlist[i]*'*')

list=[2,4,3,5]

histogram(list)

Output

>>>

**

****

***

*****

>>>
Pract 3a

Aim:write a program to check whether the sentence is panagram or not

Code :

def panagram(nt):

check="abcdefghijklmnopqrstuvw"

for i in check:

if(i in nt):

continue

else:

return False

return True

n=input("Enter Any Text:")

if(panagram(n.lower())):

print("Yes it is a Panagram")

else:

print("No it is not a Panagram")

output :

>>>

Enter Any Text:the quick brown fox jumps over the lazy dog

Yes it is a Panagram

>>>

>>> ================================ RESTART ================================

>>>

Enter Any Text:yes it ur turn to go switch the place

No it is not a Panagram
Pract 3b

Aim:write a program to check the num is less then given num.

Code :

def lessThanfivechecker(li,n):

new_li=[ele for ele in li if ele<n]

return new_li

li=[1,1,2,3,5,8,13,21,34,55,89]

print("The list is"+str(li))

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:

>>>

The list is[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

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

Aim:implement the concept of inheritance using python

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

Aim: implement the concept of inheritance using python

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

a=int(input("Enter the first no"))


b=int(input("Enter the second no"))

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.

Code: from tkinter import *

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"

messagebox.showinfo("hello python","my name is"+'%s'%svalue.get()+

"I am"+str(Radiovar.get())+

"age is"+str(scalevar.get())+

"my hobbies are" + choice)

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

sql = """INSERT INTO EMPLOYEE(FIRST_NAME,


LAST_NAME, AGE, SEX, INCOME)
VALUES ('Nitesh', 'Shukla', 23, 'M', 20000)"""
cursor.execute(sql)
print("Data Inserted Successfully...!")

sql="""select * from EMPLOYEE"""


cursor.execute(sql)
result=cursor.fetchall()
print ("inserted data is ")
for row in result:
print(row)

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

sql = "INSERT INTO student(name,rollno,marks,sub)


VALUES('"+sname.get()+"',"+sroll.get()+","+smarks.get()+",'"+ssub.get()+"')"
cursor.execute(sql)
db.commit()
print("Data Inserted Successfully...!")
messagebox.showinfo(message="information inserted")
def viewcall():
sql ="select * from student"
cursor.execute(sql)
result=cursor.fetchall()
listbox=Listbox(win,width=50)
listbox.grid(row=6,columnspan=2)
for r in result:
listbox.insert(END,list(r))
db.commit()
win=Tk()
win.title("Student Info")
Label(win,text="Name:").grid(row=0)
Label(win,text="Roll no:").grid(row=1)
Label(win,text="Marks:").grid(row=2)
Label(win,text="Subject:").grid(row=3)
sname=Entry(win,width=30)
sname.grid(row=0,column=1)
v=IntVar()
sroll=Entry(win,width=30,textvariable=v)
sroll.grid(row=1,column=1)
v1=IntVar()
smarks=Entry(win,width=30,textvariable=v1)
smarks.grid(row=2,column=1)
ssub=Entry(win,width=30)
ssub.grid(row=3,column=1)
b1=Button(win,text="insert",command=insert_method)
b1.grid(row=4)
b2=Button(win,text="view",command=viewcall)
b2.grid(row=4,column=1)
mainloop()
db.close()
OUTPUT:
Pract 10 b)
Design database application to search specific record from database(use same student
table)

from tkinter import *


import mysql.connector
db=mysql.connector.connect(host="localhost",port=3306,user="root",password="root",database
='test')
cursor = db.cursor()

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

from tkinter import *


import mysql.connector
db=mysql.connector.connect(host="localhost",port=3306,user="root",password="root",database
='test')
# prepare a cursor object using cursor() method
cursor = db.cursor()

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:

Potrebbero piacerti anche