New Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 41

Practical 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.

Program:-
name = input("What is your name? ")

age = int(input("How old are you? "))

hundred_year_old_year = 2023 + (100 - age)

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:

return fibonacci(n - 1) + fibonacci(n - 2)

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]

elif isinstance(value, list) or isinstance(value, tuple):

return value[::-1]

else:

return "Unsupported data type"

user_input = input("Enter a value: ")

reversed_value = reverse_value(user_input)

print("Reversed value:", reversed_value)

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)

armstrong_sum = sum(int(digit)**num_digits for digit in num_str)

return armstrong_sum == number

num = 153

print(is_armstrong_number(num))

def is_palindrome(number):

num_str = str(number)

reversed_str = num_str[::-1]

return num_str == reversed_str

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)

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

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

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"

return character in vowels

char = input("Enter a character: ")

if len(char) == 1:

if is_vowel(char):

print(f"{char} is a vowel.")

else:

print(f"{char} is not a vowel.")

else:

print("Please enter a single character.")

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

def ispangram(sentence, alphabet=string.ascii_lowercase):

alphaset = set(alphabet)

return alphaset<= set(sentence.lower())

print ( ispangram(input('Sentence: ')) )

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:

print ('The 2 list have at least one common element')

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]

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

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)

Output:-
(C ). Write a Python program to clone or copy a list.
Program:-
l1=[2, 4, 7, 8, 9, 0]

print ("Original List is", l1)

l2=l1

print ("Clone List is ",l2)

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}

print('Original dictionary : ',d)

sorted_d = sorted(d.items(), key=operator.itemgetter(1))

print('Dictionary in ascending order by value : ',sorted_d)

sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))

print('Dictionary in descending order by value : ',sorted_d)

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 = {}

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

L = ["Hello Sumit how are you?..."]

file1.write("NAMASTE \n")

file1.writelines(L)

file1.close()

file1 = open("myfile.txt","r+")

print ("Output of Read function is :",file1.read())

Output:-
(b) Write a Python program to append text to a file and display the text.
Program:-
def file_read(fname):

from itertools import islice

with open(fname, "w") as myfile:

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:

while len(lines) <=n:

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)

for line in lines:

print(line, end=' ')

except:

print('file not found')

Output:-
Practical 7
(a) Design a class that store the information of student and display the same.

Program:-
class student:

def info(self, name, address):

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

def __init__(self, x, y):

self.x = x

self.y = y

def add(self):

print(self.x + self.y)

def multiply(cls, a):

print(cls.MULTIPLIER * a)

def subtract(self, b, c):

self.b = b self.c = c

print(self.b - self.c)

def value(self, xy_tuple):

print(self.x, self.y)

self.x, self.y = xy_tuple

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:

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

div = 10/ num

except(ValueError, ZeroDivisonError):

print("Something is wrong")

else:

print("Division is:", div)

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 )

from tkinter import*


top = Tk()
LI = Label(top, text="User Name")
LI.pack(side = LEFT)
El = Entry(top, bd =5)
El.pack(side = RIGHT)
top.mainloop()

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

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

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

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

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

OUTPUT:

You might also like