New Python
New Python
New Python
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.
Program:-
name = input("What is your name? ")
print("Hello, {}. You will turn 100 years old in the year {}.".format(name, hundred_year_old_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.
Program:-
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is an even number.")
else:
print(f"{num} is an odd number.")
Output:-
C. Write a program to generate the Fibonacci series.
Program:-
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
for i in range(10):
print(fibonacci(i))
Output:-
D. Write a function that reverses the user defined value.
Program:-
def reverse_value(value):
if isinstance(value, str):
return value[::-1]
return value[::-1]
else:
reversed_value = reverse_value(user_input)
OUTPUT :
E. Write a function to check the input value is Armstrong and also write the function for it .
Program:-
def is_armstrong_number(number):
num_str = str(number)
num_digits = len(num_str)
num = 153
print(is_armstrong_number(num))
def is_palindrome(number):
num_str = str(number)
reversed_str = num_str[::-1]
num = 121
print(is_palindrome(num))
OUTPUT :
F. Write a recursive function to print the factorial for a given number.
Program:-
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
if num < 0:
elif num == 0:
else:
Output:-
Practical 2
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.
Program:-
def is_vowel(character):
vowels = "aeiouAEIOU"
if len(char) == 1:
if is_vowel(char):
print(f"{char} is a vowel.")
else:
else:
Output:-
B. Define a function that computes the length of a given list or string.
Program:-
def compute_length(input_data):
length = len(input_data)
return length
my_list = [1, 2, 3, 4, 5]
my_string = "Hello, world!"
list_length = compute_length(my_list)
string_length = compute_length(my_string)
print("Length of the list:", list_length)
print("Length of the string:", string_length)
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:
****
*********
*******
Program:-
def histogram(numbers):
for num in numbers:
print('*' * num)
histogram([4, 9, 7])
Output:-
Practical 3
(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.
Program:-
import string, sys
if sys.version_info[0] < 3:
input = raw_input
alphaset = set(alphabet)
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.
Program:-
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)
Output:-
Practical 4
(A) Write a program that takes two lists and returns True if they have at least one common
member.
Program:-
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:
Output:-
(B). Write a Python program to print a specified list after removing the 0th, 2nd, 4th and 5th
elements.
Program:-
l1=[1,2,3,4,5,6,7,8,9,0]
l1.remove(l1[0])
l1.remove(l1[1])
print("After Removal of 1st element of New List (original 2nd index element)is",l1)
l1.remove(l1[2])
print("After Removal of 3rd element of New List (original 4th index element)is",l1)
l1.remove(l1[2])
print (l1)
Output:-
(C ). Write a Python program to clone or copy a list.
Program:-
l1=[2, 4, 7, 8, 9, 0]
l2=l1
Output:-
Practical 5
(A) Write a Python script to sort (ascending and descending) a dictionary by value.
Program:-
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Output:-
(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}
Program:-
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
print(dic4)
Output:-
(c) Write a Python program to sum all the items in a dictionary.
Program:-
dict={'data1':140,'data2':-54,'data3':315}
print(sum(dict.values()))
Output:-
Practical 6
(a): Write a Python program to read an entire text file.
Program:-
file1 = open("myfile.txt","w")
file1.write("NAMASTE \n")
file1.writelines(L)
file1.close()
file1 = open("myfile.txt","r+")
Output:-
(b) Write a Python program to append text to a file and display the text.
Program:-
def file_read(fname):
myfile.write("Python \n")
myfile.write("Data structure")
txt = open(fname)
print(txt.read())
file_read('abc')
Output:-
(c) Write a Python program to read last n lines of a file.
Program:-
def Lastlines(fname, n):
assert n>=0
pos = n +1
lines = []
with open(fname) as f:
try:
f.seek(-pos, 2)
except IOError:
f.seek(0)
break
finally:
lines = list(f)
pos *= 2
print(lines[-n:])
if __name__ == '__main__':
fname = 'myfile.txt'
n=3
try:
lines = Lastlines(fname, n)
except:
Output:-
Practical 7
(a) Design a class that store the information of student and display the same.
Program:-
class student:
print("Name:",name)
print("Address:",address)
s = student()
s.info('Karan' ,'Panvel')
Output:-
(b) Implement the concept of inheritance using python.
Program:-
class st:
def c1(self):
print("Base class")
class st1(st):
def c2(self):
print("Derived class")
s = st1()
s.c1()
s.c2()
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.
Program:-
class Numbers:
MULTIPLIER = 3.5
self.x = x
self.y = y
def add(self):
print(self.x + self.y)
print(cls.MULTIPLIER * a)
self.b = b self.c = c
print(self.b - self.c)
print(self.x, self.y)
del self.x
del self.y
n = Numbers(10, 20)
n.add()
n.multiply(30)
n.subtract(50, 40)
n.value((10,20))
OUTPUT :
PRACTICAL 8
(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 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.
PROGRAM :
import math
def sphereArea(r):
print(4*math.pi*r**2)
def sphereVolume(r):
print(4*math.pi*r**3/3)
def sphereMatrics(r):
sphereArea(r)
sphereVolume(r)
def circleArea(r):
print(math.pi*r**2)
def squareArea(x):
print(x**2)
sphereMatrics(5)
print("-----------------------------------------------")
def pointyShapeVolume(x,h,square):
if (square == True):
base = squareArea(x)
else:
base = int(circleArea(x))
a = base/3
print(h*a)
print(pointyShapeVolume(3,4, True)
OUTPUT:
(b) Write a program to implement exception handling
try:
except(ValueError, ZeroDivisonError):
print("Something is wrong")
else:
OUTPUT:
PRACTICAL 9
(a) Try to configure the widget with various options like: bg=”red” , family=”times” , size=18
.
Program :
import tkinter as tk
root = tk.Tk()
frame = tk.Frame(root)
def dosomething():
mylabel.config(text = "Goodbye World....")
mylabel = tk.Label(frame, text = "Hello World....", bg = "red") mylabel.pack(padx = 5, pady =
10)
mybutton = tk.Button(frame, text = "Click Me", command = dosomething)
mybutton.pack(padx = 5, pady = 10)
frame.pack(padx = 5, pady = 5)
root.mainloop()
OUTPUTt:
(b) Try to change the widget type and configuration options to experiment with other
widget types like Message, Button, Entry, Checkbutton, Radiobutton, Scale etc.
Program:
(Message)
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 )
import tkinter
from tkinter import*
top = tkinter.Tk()
def helloCallBack():
tkinter.meessagebox.showinfo( "Hello Python", "Hello World") B=tkinter.Button(top,
text="hello" ,command = helloCallBack) B.pack()
top.mainloop()
OUTPUT:
( Entry )
OUTPUT:
( Checksum )
Program:
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)
PROGRAM:
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="Number 1", variable=var, value=1, command=sel)
R1.pack( anchor = W)
R2 =Radiobutton(root, text="Number 2", variable=var, value=2, command=sel)
R2.pack( anchor = W)
R3= Radiobutton(root, text="Number 3",
variable=var, value=3,
command=sel)
R3.pack( anchor = W)
label = Label(root)
label.pack()
root.mainloop()
OUTPUT:
PRACTICAL 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.
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')
cursor = db.cursor()
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
cursor.execute(sql)
db.close()
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='p ython_mysql')
cursor = db.cursor()
sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Nitesh',
'Shukla', 23, 'M', 20000)"""
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
B. Design a database application to search the specified record from the database.
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')
cursor = db.cursor()
try:
cursor.execute(sql)
results = cursor.fetchall()
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
except:
db.close()
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()
OUTPUT:
Delete.py
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
Update.py
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n it')
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
OUTPUT: