T.Y.B.B.A.(C.A.) Semester - V Practical Examination. Lab Course: (CA-506) Computer Lab Based on Python Solved slips

T.Y.B.B.A.(C.A.) Semester – V (CBCS 2019 Pattern) University Practical Examination Lab Course: (CA-506) Python 





Slip 1

A) Write a Python program to accept n numbers in list and remove duplicates from a list. [15 M]


CODE :

marks =[]
n=int(input('Enter number of elements : '))
for i in range(n):
    value=int(input())
    marks.append(value)
print(marks)
new_marks=[]
for x in marks:
    if x not in new_marks:
        new_marks.append(x)
print(new_marks)




 B) Write a Python GUI program to take accept your birthdate and output your age when a button is pressed. [25 M]

CODE :

from tkinter import *  
from tkinter import messagebox  


def clearAll() :  
    dayField.delete(0, END)
    monthField.delete(0, END)
    yearField.delete(0, END)
    givenDayField.delete(0, END)
    givenMonthField.delete(0, END)
    givenYearField.delete(0, END)
    rsltDayField.delete(0, END)
    rsltMonthField.delete(0, END)
    rsltYearField.delete(0, END)

def checkError() :

    if (dayField.get() == "" or monthField.get() == ""
        or yearField.get() == "" or givenDayField.get() == ""
        or givenMonthField.get() == "" or givenYearField.get() == "") :

        messagebox.showerror("Input Error")  

        clearAll()
       
        return -1

def calculateAge() :  
    value = checkError()  
    if value == -1 :
        return      
    else :
       
        birth_day = int(dayField.get())    
        birth_month = int(monthField.get())
        birth_year = int(yearField.get())  

        given_day = int(givenDayField.get())    
        given_month = int(givenMonthField.get())
        given_year = int(givenYearField.get())  
       
        month =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]       
        if (birth_day > given_day):  
            given_month = given_month - 1  
            given_day = given_day + month[birth_month-1]
                   
        if (birth_month > given_month):
            given_year = given_year - 1
            given_month = given_month + 12
                   
        calculated_day = given_day - birth_day;        
        calculated_month = given_month - birth_month;  
        calculated_year = given_year - birth_year;    

        rsltDayField.insert(10, str(calculated_day))
        rsltMonthField.insert(10, str(calculated_month))
        rsltYearField.insert(10, str(calculated_year))  
   
if __name__ == "__main__" :

    gui = Tk()      
    gui.configure(background = "light green")
    gui.title("Age Calculator")    
    gui.geometry("525x260")    
 
 
 
    dob = Label(gui, text = "Date Of Birth", bg = "#00ffff")
 
 

    givenDate = Label(gui, text = "Given Date", bg = "#00ffff")

    day = Label(gui, text = "Day", bg = "light green")
    month = Label(gui, text = "Month", bg = "light green")
    year = Label(gui, text = "Year", bg = "light green")

    givenDay = Label(gui, text = "Given Day", bg = "light green")
    givenMonth = Label(gui, text = "Given Month", bg = "light green")
    givenYear = Label(gui, text = "Given Year", bg = "light green")

    rsltYear = Label(gui, text = "Years", bg = "light green")
    rsltMonth = Label(gui, text = "Months", bg = "light green")
    rsltDay = Label(gui, text = "Days", bg = "light green")


    resultantAge = Button(gui, text = "Resultant Age", fg = "Black",
                     bg = "gray", command = calculateAge)


    clearAllEntry = Button(gui, text = "Clear All", fg = "Black",
                    bg = "Red", command = clearAll)

    dayField = Entry(gui)
    monthField = Entry(gui)
    yearField = Entry(gui)
   
    givenDayField = Entry(gui)
    givenMonthField = Entry(gui)
    givenYearField = Entry(gui)
   
    rsltYearField = Entry(gui)
    rsltMonthField = Entry(gui)
    rsltDayField = Entry(gui)

    dob.grid(row = 0, column = 1)
   
    day.grid(row = 1, column = 0)
    dayField.grid(row = 1, column = 1)
   
    month.grid(row = 2, column = 0)
    monthField.grid(row = 2, column = 1)
   
    year.grid(row = 3, column = 0)
    yearField.grid(row = 3, column = 1)
   
    givenDate.grid(row = 0, column = 4)
   
    givenDay.grid(row = 1, column = 3)
    givenDayField.grid(row = 1, column = 4)
   
    givenMonth.grid(row = 2, column = 3)
    givenMonthField.grid(row = 2, column = 4)
   
    givenYear.grid(row = 3, column = 3)
    givenYearField.grid(row = 3, column = 4)
   
    resultantAge.grid(row = 4, column = 2)
   
    rsltYear.grid(row = 5, column = 2)
    rsltYearField.grid(row = 6, column = 2)
   
    rsltMonth.grid(row = 7, column = 2)
    rsltMonthField.grid(row = 8, column = 2)
   
    rsltDay.grid(row = 9, column = 2)
    rsltDayField.grid(row = 10, column = 2)

    clearAllEntry.grid(row = 12, column = 2)

    gui.mainloop()








Slip 2


A) Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. Sample String: 'The quick Brown Fox' Expected Output: No. of Upper case characters: 3 No. of Lower case characters: 13 [15 M] 


CODE :


string=input('enter a string : ')
up=low=ele=0
for x in string:  
    if x.isupper():
        up+=1
    elif x.islower():
        low+=1
    else:
        ele+=1
print('No. of Upper case characters : ',up)
print('No. of Lower case characters : ',low)
print('other special symbols',ele)


B) Write Python GUI program to create a digital clock with Tkinter to display the time. [25 M] 

 

CODE :




from tkinter import *
from tkinter.ttk import *
 
from time import strftime  
 
root = Tk()
root.title('Clock')

def time():
    string = strftime('%H:%M:%S %p')
    lbl.config(text = string)
    lbl.after(1000, time)

lbl = Label(root, font = ('calibri', 40, 'bold'),
            background = 'purple',
            foreground = 'white')
 
lbl.pack(anchor = 'center')  
time()  
 
mainloop()




Slip 3

A) Write a Python program to check if a given key already exists in a dictionary. If key exists replace with another key/value pair. [15 M] 


CODE :



Dict={}
n=int(input('enter number of keys :'))
for x in range(0,n):
    key=input('enter the key :')
    if key in Dict:
        print('the given key exists!')
       
        for key in Dict.keys():
            print(key,end=' ')
        print('\n ^ use differnt keys from above list')
        key=input('enter the key :')
    value=input('enter the value :')
    Dict[key]=value
print(Dict)




B) Write a python script to define a class student having members roll no, name, age, gender. Create a subclass called Test with member marks of 3 subjects. Create three objects of the Test class and display all the details of the student with total marks. [25 M] 

Code :



class Student():
    def __init__(self,roll_no,name,age,gender):
        self.roll_no=roll_no
        self.name=name
        self.age=age
        self.gender=gender

class Test(Student):
    def __init__(self,roll_no,name,age,gender,sub1mark,sub2mark,sub3mark,):
        super().__init__(roll_no,name,age,gender)
        self.mark1=sub1mark
        self.mark2=sub2mark
        self.mark3=sub3mark
   
    def get_marks(self):
        self.total=self.mark1+self.mark2+self.mark3
        print(self.name , "\b's marks:", self.total)
        print("sub1 marks :",self.mark1)
        print("sub2 marks :",self.mark2)
        print("sub3 marks :",self.mark3)
       
p1=Test(1,"amar",19,'male',82,89,76)
p2=Test(2,'priya',20,'female',94,91,84)
p1.get_marks()
p2.get_marks()

 

Slip 4


A) Write Python GUI program to create background with changing colors [15 M] 

CODE :



from tkinter import Button, Entry, Label, Tk


def changecolor():
    newvalue = value.get()
    gui.configure(background = newvalue)
   
gui=Tk()
gui.title("color change.")
gui.configure(background = "gray")
gui.geometry("400x300")

color = Label(gui, text = "color", bg = "gray")
value = Entry(gui)
apply = Button(gui, text = "Apply", fg = "Black", bg = "gray", command = changecolor)

color.grid(row=0,column=0)
value.grid(row=0,column=1)
apply.grid(row=0,column=2)

gui.mainloop()


B) Define a class Employee having members id, name, department, salary. Create a subclass called manager with member bonus. Define methods accept and display in both the classes. Create n objects of the manager class and display the details of the manager having the maximum total salary (salary+bonus). [25 M] 

CODE :


class Employee:
    def __init__(self, id, name, department, salary):
        self.id=id
        self.name=name
        self.department=department
        self.salary=salary
       
class manager(Employee):
    def __init__(self, id, name, department, salary ,bonus):
        super(manager, self).__init__(id, name, department, salary)
        self.bonus=bonus
       
    def totalsalary(self):
        print(self.name,'got total salary :',self.salary+self.bonus)
       
n=manager('A023','AMAR','GENERAL MANAGEMENT',20000,8000)
m=manager('A025','priya','MARKETIG',25000,6400)
n.totalsalary()
m.totalsalary()






Slip 5

A) Write a Python script using class, which has two methods get_String and print_String. get_String accept a string from the user and print_String print the string in upper case. [15 M] 

CODE :

class Str1():
    def __init__(self,demo=0):
        self.demo=demo
       
    def set_String(self,demo):
        self.demo=demo
   
    def print_streing(self):
        str=self.demo
        print(str.upper())
       
A=Str1()
rowinput=input('enter a string :')
A.set_String(rowinput)
A.print_streing()


B) Write a python script to generate Fibonacci terms using generator function. [25 M]

CODE :



def generator(r):
    a=0;b=1
    for i in range (1,r):
        print(b)
        a,b=b,a+b
       
n=int(input('Enter a number :'))
if n==0:
    print('0')
else:
    print(0)
    generator(n)




Slip 6


A) Write python script using package to calculate area and volume of cube and sphere [15 M] 

CODE:


import math

class cube():
    def __init__(self,edge):
        self.edge=edge
       
    def cube_area(self):
        cubearea=6*self.edge*self.edge
        print("Area of cube :",cubearea)
   
    def cube_volume(self):
        cubevolume=self.edge*self.edge*self.edge
        print("Volume of cube :",cubevolume)

class sphere():
    def __init__(self,radius):
        self.radius=radius
       
    def sphere_area(self):
        spherearea=4*math.pi*self.radius*self.radius
        print("Area of sphere :",spherearea)
       
    def sphere_volume(self):
        spherevolume=float(4/3*math.pi*self.radius**3)
        print("volume of sphere :",spherevolume)
       
e1=cube(5)
e1.cube_area()
e1.cube_volume()

r1=sphere(5)
r1.sphere_area()
r1.sphere_volume()



B) Write a Python GUI program to create a label and change the label font style (font name, bold, size). Specify separate check button for each style. [25 M] 


CODE:
import tkinter as tk parent = tk.Tk() parent.title("-Welcome to Python tkinter Basic exercises-") my_label = tk.Label(parent, text="Hello", font=("Arial Bold", 70)) my_label.grid(column=0, row=0) parent.mainloop()




Slip 7


A) Write Python class to perform addition of two complex numbers using binary + operator overloading. [15 M] 

CODE :

class Complex ():
    def initComplex(self):
        self.realPart = int(input("Enter the Real Part: "))
        self.imgPart = int(input("Enter the Imaginary Part: "))            

    def display(self):
        print(self.realPart,"+",self.imgPart,"i", sep="")

    def sum(self, c1, c2):
        self.realPart = c1.realPart + c2.realPart
        self.imgPart = c1.imgPart + c2.imgPart

c1 = Complex()
c2 = Complex()
c3 = Complex()

print("Enter first complex number")
c1.initComplex()
print("First Complex Number: ", end="")
c1.display()

print("Enter second complex number")
c2.initComplex()
print("Second Complex Number: ", end="")
c2.display()

print("Sum of two complex numbers is ", end="")
c3.sum(c1,c2)
c3.display()



B) Write python GUI program to generate a random password with upper and lower case letters.

CODE :

import string,random
from tkinter import *

def password():
    clearAll()
    String = random.sample(string.ascii_letters, 6) + random.sample(string.digits, 4)
    random.SystemRandom().shuffle(String)
    password=''.join(String)
    passField.insert(10, str(password))

def clearAll() :
    passField.delete(0, END)

if __name__ == "__main__" :

    gui = Tk()
    gui.configure(background = "light green")
    gui.title("random password")
    gui.geometry("325x150")

    passin = Label(gui, text = "Password", bg = "#00ffff").pack()
    passField = Entry(gui);passField.pack()
   
    result = Button(gui,text = "Result",fg = "Black",
                    bg = "gray", command = password).pack()
    clearAllEntry = Button(gui,text = "Clear All",fg = "Black",
                    bg = "Red", command = clearAll).pack()


gui.mainloop()



Slip 8


A) Write a python script to find the repeated items of a tuple [15 M] 

CODE :

import collections

tuplex = 2,4,5,6,2,3,4,4,7,5,6,7,1

dictx=collections.defaultdict(int)
for x in tuplex:
    dictx[x]+=1
for x in sorted(dictx,key=dictx.get):
    if dictx[x]>1:
        print('%d repeted %d times'%(x,dictx[x]))



B) Write a Python class which has two methods get_String and print_String. get_String accept a string from the user and print_String print the string in upper case. Further modify the program to reverse a string word by word and print it in lower case. [25 M]

CODE :

class Str1():
    def __init__(self,demo=0):
        self.demo=demo
       
    def set_String(self,demo):
        demo=demo.upper()
        self.demo=demo
   
    def print_streing(self):
       
        return self.demo
       
A=Str1()
str1=input('enter a string to display :')
A.set_String(str1)
print('Upper string :',A.print_streing())




Slip 9


A) Write a Python script using class to reverse a string word by word [15 M] 

CODE :

METHOD 1

def reverse_words(s):
    return ' '.join(reversed(s.split()))

str1=input('Enter a string : ')
print(reverse_words(str1))
METHOD 2

def listtostr(strlist):
    newstr=""
    for X in strlist:
        newstr += X+' '
    return newstr

str1=input("Enter a string to reverse : ")
strlist=str1.split(" ")
strlist.reverse()
print(listtostr(strlist))



B) Write Python GUI program to accept a number n and check whether it is Prime, Perfect or Armstrong number or not. Specify three radio buttons. [25 M]

CODE:

from tkinter import*


def perfect():
    number=int(numberFeald.get())
    count = 0
    for i in range(1, number):
        if number % i == 0:
            count = count + i
    if count == number:
        perfect1.select()
        print(number, 'The number is a Perfect number!')
    else:
        perfect1.deselect()
        print(number, 'The number is not a Perfect number!')

def armstrong():
    number=int(numberFeald.get())
    count = 0
    temp = number
    while temp > 0:
        digit = temp % 10
        count += digit ** 3
        temp //= 10
    if number == count:
        armstrong1.select()
        print(number, 'is an Armstrong number')
    else:
        armstrong1.deselect()
        print(number, 'is not an Armstrong number')

def prime():
    number=int(numberFeald.get())
    if number > 1:
        for i in range(2,number):
            if (number % i) == 0:
                prime1.deselect()
                print(number,"is not a prime number")
                print(i,"times",number//i,"is",number)
                break
            else:
                prime1.select()
                print(number,"is a prime number")
    else:
        prime1.deselect()
        print(number,"is not a prime number")
       
root=Tk()
root.title('Prime, Perfect or Armstrong number')
root.geometry('300x200')
numberFeald=Entry(root)
numberFeald.pack()

Button1=Button(root,text='Button',command=lambda:[armstrong(),prime(),perfect()])
Button1.pack()

prime2=IntVar()
perfect2=IntVar()
armstrong2=IntVar()

armstrong1=Radiobutton(root,text='armstrong',variable=armstrong2,value=1)
prime1=Radiobutton(root,text='prime',variable=prime2,value=1)
perfect1=Radiobutton(root,text='perfect',variable=perfect2,value=1)
armstrong1.pack()
prime1.pack()
perfect1.pack()

root.mainloop()



Slip 10


A) Write Python GUI program to display an alert message when a button is pressed. [15 M] 

CODE :

from tkinter import *
from tkinter import messagebox

def clicked():
    messagebox.showinfo('Button','Button is pressed.')
root=Tk()
root.geometry('300x200')
word= Label(root,text='messagebox from button')
Button1=Button(root,text='BUTTON',command=clicked)
word.pack()
Button1.pack()
root.mainloop()


B) Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '[' ']’. These brackets must be close in the correct order. for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid. [25 M]


class py_solution: def is_valid_parenthese(self, str1): stack, pchar = [], {"(": ")", "{": "}", "[": "]"} for parenthese in str1: if parenthese in pchar: stack.append(parenthese) elif len(stack) == 0 or pchar[stack.pop()] != parenthese: return False return len(stack) == 0 print(py_solution().is_valid_parenthese("(){}[]")) print(py_solution().is_valid_parenthese("()[{)}")) print(py_solution().is_valid_parenthese("()"))




Slip 11

A) Write a Python program to compute element-wise sum of given tuples. Original lists: (1, 2, 3, 4) (3, 5, 2, 1) (2, 2, 3, 1) Element-wise sum of the said tuples: (6, 9, 8, 6) [15 M]

CODE:

Original lists: (1, 2, 3, 4) (3, 5, 2, 1) (2, 2, 3, 1) 

Element-wise sum of the said tuples: (6, 9, 8, 6)


x = (1,2,3,4);y = (3,5,2,1);z = (2,2,3,1)

print("Original lists:")
print(x)
print(y)
print(z)

print("\nElement-wise sum of the said tuples:")

result = tuple(map(sum, zip(x, y, z)))
print(result)


B) Write Python GUI program to add menu bar with name of colors as options to change the background color as per selection from menu option. [25 M]


CODE :

from tkinter import Menu, Tk, mainloop

def redcolor():
    root.configure(background = 'red')
def greencolor():
    root.configure(background = 'green')
def yellowcolor():
    root.configure(background = 'yellow')
def violetcolor():
    root.configure(background = 'violet')
def bluecolor():
    root.configure(background = 'blue')
def cyancolor():
    root.configure(background = 'cyan')
   
root = Tk()
root.title('COLOR MENU')

menubar = Menu(root)

color = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='color', menu = color)
color.add_command(label ='Red', command = redcolor,activebackground='red',
                    activeforeground='cyan')

color.add_command(label ='Green',command = greencolor,activebackground='green',
                    activeforeground='blue')

color.add_command(label ='Blue',command = bluecolor,activebackground='blue',
                    activeforeground='yellow')

color.add_command(label ='Yellow',command = yellowcolor,activebackground='yellow',
                    activeforeground='blue')

color.add_command(label ='Cyan',command = cyancolor,activebackground='cyan',
                    activeforeground='red')

color.add_command(label ='Violet',command = violetcolor,activebackground='violet',
                    activeforeground='green')
color.add_separator()
color.add_command(label ='Exit',command = root.destroy)


root.config(menu = menubar)
mainloop()



Slip 12


A) Write a Python GUI program to create a label and change the label font style (font name, bold, size) using tkinter module. [15 M] 

CODE:



from tkinter import Label, Tk
top=Tk()
top.title="font style"
label=Label(top,text="this is text with style",font=("Helvetica",25))
label.pack()
top.mainloop()


B) Write a python program to count repeated characters in a string. 

Sample string: 'thequickbrownfoxjumpsoverthelazydog' 

Expected output: o-4, e-3, u-2, h-2, r-2, t-2 [25 M] 


CODE :

Sample string: 'thequickbrownfoxjumpsoverthelazydog'
 Expected output: o-4, e-3, u-2, h-2, r-2, t-2


import collections

str1 = input('Enter a string : ')

d = collections.defaultdict(int)

for c in str1:
    if c ==' ':
        continue
    d[c] += 1

for c in sorted(d, key=d.get):
    if d[c] > 1:
        print('%s - %d' % (c, d[c]))





A) Write a Python program to input a positive integer. Display correct message for correct and incorrect input. (Use Exception Handling)

 Slip 13 Q 1

CODE:


try:
    num=int(input('Enter a number :'))
except ValueError:
    print("\nThis is not a number!")
else:
    print('\nnumber is : ',num)





Write a program to implement the concept of queue using list.

Slip 13 Q 2

CODE :

Note rule of a queue:  The order is First In First Out (FIFO).

q=[]

q.append(10)
print("Initial Queue is:",q)
q.append(100)
print("Initial Queue is:",q)
q.append(1000)
print("Initial Queue is:",q)
q.append(10000)
print("Initial Queue is:",q)

print('{} is out from queue ! '.format(q.pop(0)))
print("After Removing elements:",q)
print('{} is out from queue ! '.format(q.pop(0)))
print("After Removing elements:",q)
print('{} is out from queue ! '.format(q.pop(0)))
print("After Removing elements:",q)







Write a Python GUI program to accept dimensions of a cylinder and display the surface area and volume of cylinder.

Slip 14 Q 1

CODE :

from tkinter import *
from math import pi
from tkinter import messagebox

def clearAll() :
    RadiusField.delete(0, END)
    HeightField.delete(0, END)
    volumeField.delete(0, END)
    areaField.delete(0,END)
 
def checkError() :
    if (RadiusField.get() == "" or HeightField.get() == "") :
        messagebox.showerror("Input Error")
        clearAll()
        return -1

def result() :
    value = checkError()
    if value == -1 :
        return
    else :
        Radius = int(RadiusField.get())
        Height = int(HeightField.get())
       
        volume=round(pi*Height*Radius**2,2)
        area=round((2*pi*Radius*Height)+(2*pi*Radius**2),2)
       
        volumeField.insert(10, str(volume))
        areaField.insert(10, str(area))
 
if __name__ == "__main__" :

    gui = Tk()
    gui.configure(background = "light green")
    gui.title("cylinder surface area and volume of cylinder")
    gui.geometry("300x175")
 
 
 
    radius = Label(gui, text = " give radius", bg = "#00ffff")
    height = Label(gui, text = "give height", bg = "#00ffff")
    area = Label(gui, text = "Area", bg = "#00ffff")
    volume = Label(gui, text = "Volume", bg = "#00ffff")
   
    resultlabel = Label(gui, text = "RESULT", bg = "#00ffff")
   
    resultbutton = Button(gui, text = "Result", fg = "Black",
                        bg = "gray", command = result)
    clearAllEntry = Button(gui, text = "Clear All", fg = "Black",
                        bg = "Red", command = clearAll)

    RadiusField = Entry(gui)
    HeightField = Entry(gui)
    volumeField = Entry(gui)
areaField =Entry(gui)

radius.grid(row = 0, column = 0)
height.grid(row = 0, column = 2)
area.grid(row = 2, column = 0)
volume.grid(row = 2, column = 2)

resultlabel.grid(row = 4, column = 1)
resultbutton.grid(row = 5, column = 1)
   
RadiusField.grid(row = 1, column = 0)
HeightField.grid(row = 1, column = 2)

areaField.grid(row=3,column=0)
volumeField.grid(row = 3, column = 2)
clearAllEntry.grid(row = 6, column = 1)

gui.mainloop()



Write a Python program to display plain text and cipher text using a Caesar encryption.

Slip 14 Q 2

CODE :


def encypt_func(txt, s):  
    result = ""  
    for i in range(len(txt)):  
        char = txt[i]
        if (char.isupper()):  
            result += chr((ord(char) + s - 64) % 26 + 65)
        else:  
            result += chr((ord(char) + s - 96) % 26 + 97)  
    return result  

txt = input('Enter a string : ')
s = int(input('ENtER number to shift pattern encript : '))
 
print("Plain txt : " + txt)  
print("Shift pattern : " + str(s))  
print("Cipher: " + encypt_func(txt, s))  




A) Define an Interface Shape with abstract method area(). Write a java program to calculate an area of Circle and Sphere.(use final keyword)

 Slip 8 Q 1

Save code as             "InterfaceCircleSphere.java"


import java.util.Scanner;

interface Shape{
    void area();
}
class Circle implements Shape{
    final float PI=3.14f;
    float areacircle,radius;
    Scanner s=new Scanner(System.in);
    void accept(){
        System.out.print("Enter the Radius of circle : ");
        radius=s.nextFloat();
    }
    public void area(){
    areacircle=PI*radius*radius;
    }
    public void show()
    {
    System.out.println("Area of circle is : "+areacircle);
    }
}

class Sphere implements Shape{
    final float PI=3.14f;
    float areasphere,radius;
    Scanner s=new Scanner(System.in);
    void accept(){
        System.out.print("Enter the Radius of sphere : ");
        radius=s.nextFloat();
    }
    public void area(){
        areasphere=4*PI*radius*radius;
    }
    public void show(){
        System.out.println("Area of Sphere is : "+areasphere);
    }
}
class InterfaceCircleSphere
{
    public static void main(String args[]){
        Circle s1=new Circle();
        s1.accept();
        s1.area();
        s1.show();
        Sphere s2=new Sphere();
        s2.accept();
        s2.area();
        s2.show();
    }
}




Write a Python class named Student with two attributes student_name, marks. Modify the attribute values of the said class and print the original and modified values of the said attributes.

Slip 15 Q 1

CODE :


class Student:
    def __init__(self, Student_name, marks):
        self.Student_name=Student_name
        self.marks=marks
   
    def get_marks(self):
        print("\nOriginal name and values")
        print(self.Student_name,'marks : ',self.marks)
       
    def modify_marks(self):
        self.Student_name1=input('Enter modifyed name : ')
        self.marks1=int(input('Enter modifyed marks : '))
        print(self.Student_name1,'modifyed marks',self.marks)
       
    def modifyed_marks(self):
        print("\nmodified name and values")
        print(self.Student_name1,'marks : ',self.marks1)
       
x=Student('AMAR',81)
x.get_marks()
x.modify_marks()

x.get_marks()
x.modifyed_marks()



Write a python program to accept string and remove the characters which have odd index values of given string using user defined function.

Slip 15 Q 2

CODE :


def removeodd(string):
    str2=''
    for x in range(len(string)):
        if x%2==0:
            str2=str2+string[x]
    return str2
str1=input('enter a string : ')
print('String after removing char : ',removeodd(str1))




Write a python script to create a class Rectangle with data member’s length, width and methods area, perimeter which can compute the area and perimeter of rectangle.

Slip 16 Q 1

CODE :


class Ractangle():
    def __init__(self,l,w):
        self.l=l
        self.w=w
    def rectangle_area(self):
        return self.l*self.w
    def rectangle_Perimeter(self):
        return (self.l*2)+(self.w*2)
   
L=int(input('enter Length  of Rectangle :'))
W=int(input('enter Width  of Rectangle :'))
a1=Ractangle(L,W)
print(a1.rectangle_area())
print(a1.rectangle_Perimeter())








Write Python GUI program that takes input string and change letter to upper case when a button is pressed.

Slip 17 Q 1

CODE:


from tkinter import *
from tkinter import messagebox

def clearAll() :
    str1Field.delete(0, END)
    altersField.delete(0, END)
   
def checkError() :
    if (str1Field.get() == "" ) :
        messagebox.showerror("Input Error")
        clearAll()
        return -1

def upper() :
    value = checkError()
    if value == -1 :
        return
    else :
        String0 = (str1Field.get())
       
        newstr=String0.upper()
       
       
        altersField.insert(20, str(newstr))
       
if __name__ == "__main__" :
    gui = Tk()
    gui.configure(background = "light green")
    gui.title("upper case")
    gui.geometry("250x200")
   
    Stringin = Label(gui, text = " given String", bg = "#00ffff")
    str1 = Label(gui, text = "String", bg = "light green")
    str1Field = Entry(gui)
   
    result = Button(gui, text = "Result", fg = "Black",
                bg = "gray", command = upper)
   
    alters = Label(gui, text = "upper case string", bg = "light green")
    altersField = Entry(gui)
   
    clearAllEntry = Button(gui, text = "Clear All", fg = "Black",
                bg = "Red", command = clearAll)


Stringin.grid(row = 0, column = 1)
str1.grid(row = 1, column = 0)
str1Field.grid(row = 1, column = 1)
   

alters.grid(row = 2, column = 0)
altersField.grid(row = 2, column = 1)
clearAllEntry.grid(row = 3, column = 0)
result.grid(row = 3, column = 1)
gui.mainloop()



Create a list a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a python program that prints out all the elements of the list that are less than 5

Slip 18 Q 1

CODE:


list1 =[]
list3=[]
list2=[]
n=int(input('Enter number of elements : '))
for i in range(n):
    value=int(input())
    list1.append(value)
print(list1)
n=int(input('Enter a number to sort list : '))

for i in list1:
    if n > i:
        list2.append(i)
    else:
        list3.append(i)
print('less then {} value list : '.format(n),list2)
print('greater then {} value list :'.format(n),list3)



Write a python script to define the class person having members name, address. Create a subclass called Employee with members staffed salary. Create 'n' objects of the Employee class and display all the details of the employee.

Slip 18 Q 2

CODE:

class person:
    def __init__(self,name,address):
        self.empname=name
        self.address=address
       
    def display(self):
        print('name : {}\taddress : {}\tsalary : {}'.format(self.empname,
        self.address,a.getsalary()))
   
class employee(person):
    def __init__(self, name, address,salary):
        super().__init__(name, address)
        self.salary=salary
       
    def getsalary(self):
        return self.salary
name1=input('enter name : ')
address=input('enter address : ')
salary=int(input('enter salary : '))
a=employee(name1,address,salary)
a.display()




Write a Python GUI program to accept a number form user and display its multiplication table on button click.

Slip 19 Q 1

CODE :

from tkinter import *

def clearAll() :
    numberField.delete(0, END);Lb1.delete(0,END)
def multiplication():
    num = int(numberField.get())
    Lb1.insert(0, '{} X 1 = {}'.format(num,1*num))
    Lb1.insert(1, '{} X 2 = {}'.format(num,2*num))
    Lb1.insert(2, '{} X 3 = {}'.format(num,3*num))
    Lb1.insert(3, '{} X 4 = {}'.format(num,4*num))
    Lb1.insert(4, '{} X 5 = {}'.format(num,5*num))
    Lb1.insert(5, '{} X 6 = {}'.format(num,6*num))
    Lb1.insert(6, '{} X 7 = {}'.format(num,7*num))
    Lb1.insert(7, '{} X 8 = {}'.format(num,8*num))
    Lb1.insert(8, '{} X 9 = {}'.format(num,9*num))
    Lb1.insert(9,'{} X 10 = {}'.format(num,10*num))
if __name__=="__main__" :
    gui = Tk()
    gui.configure(background = "light green")
    gui.title("multiplication table")
    gui.geometry("400x300")
    label=Label(gui,text='multiplication table \
                on button click').pack(side=TOP,fill=BOTH)
    number = Label(gui, text = "Give number", bg = "#00ffff").pack(fill=BOTH)
    numberField = Entry(gui)
    numberField.pack()
    resultbutton = Button(gui, text = "Result button",
                fg = "Black", bg = "gray",command=multiplication).pack()

Lb1 = Listbox(gui,fg='yellow',width=30,bg='gray',bd=1,activestyle='dotbox')

clearAllEntry = Button(gui, text = "Clear All",
            fg = "Black", bg = "gray", command = clearAll).pack(side=BOTTOM)

Lb1.pack()
gui.mainloop()



Write a python program to create a class Circle and Compute the Area and the circumferences of the circle.(use parameterized constructor)

Slip 20 Q 1

CODE :

from math import pi
class Circle():
    def __init__(self,Radius):
        self.Radius=Radius
    def area(self):
        a=pi*self.Radius*self.Radius      
        return round(a,2)
    def circumference(self):
        c=2*self.Radius*pi
        return round(c,2)
   
r= int(input('enter radius of circle : '))
a=Circle(r)
print('Area of circle is : ',a.area())
print('Circumference of circle is : ',a.circumference())



Write a Python script to generate and print a dictionary which contains a number (between 1 and n) in the form(x,x*x).

Slip 20 Q 2

CODE :


n=int(input("Input a number : "))
d ={}
for x in range(1,n+1):
    d[x]=x*x
print(d)





Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area and Perimeter

Slip 21 Q 1

CODE:


class Ractangle():
    def __init__(self,l,w):
        self.l=l
        self.w=w
    def rectangle_area(self):
        return self.l*self.w
    def rectangle_Perimeter(self):
        return (self.l*2)+(self.w*2)
   
L=int(input('enter Length  of Rectangle :'))
W=int(input('enter Width  of Rectangle :'))
a1=Ractangle(L,W)
print(a1.rectangle_area())
print(a1.rectangle_Perimeter())




Write a Python program to convert a tuple of string values to a tuple of integer values

Slip 21 Q 2

CODE :


tup1=(('333','33'),('1416','55'))
a,b=tup1
newlista=[]
newlistb=[]
arr=[]
for i in a:
    newlista.append(int(i))
arr.append(newlista)
for i in b:
    newlistb.append(int(i))
arr.append(newlistb)
finaltup=tuple(map(tuple, arr))
print(finaltup)




Write a python script to implement bubble sort using list

Slip 22 Q 2

CODE :


def bubble_sort(list1):
    for i in range(0,len(list1)-1):  
        for j in range(len(list1)-1):  
            if(list1[j]>list1[j+1]):  
                temp = list1[j]  
                list1[j] = list1[j+1]  
                list1[j+1] = temp  
    return list1  
 
list1 =[]
n=int(input('Enter number of elements : '))
for i in range(n):
    value=int(input())
    list1.append(value)
print("The unsorted list is: ", list1)  

print("The sorted list is: ", bubble_sort(list1))








Post a Comment

0 Comments