Showing posts with label PYTHON. Show all posts
Showing posts with label PYTHON. Show all posts

Tuesday, 25 January 2022

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

 SLIP 12 Q 1

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



OUTPUT:






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)

OUTPUT:




Monday, 24 January 2022

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.

 Slip 9 Q 2

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



OUTPUT:







Python Program to Create a Class in which One Method Accepts a String from the User and Another method Prints it.

Slip 30 Q 2

CODE :

class stringmethod():
    def __init__(self):
        self.string=""
 
    def get(self):
        self.string=input("Enter string: ")
 
    def put(self):
        print("String is:")
        print(self.string)

obj=stringmethod()
obj.get()
obj.put()


OUTPUT:



Write a Python GUI program to accept a string and a character from user and count the occurrences of a character in a string.

Slip 30 Q 1

CODE :


from tkinter import *
from tkinter import messagebox

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

def occurrences() :
    value = checkError()
    if value == -1 :
        return
    else :
        String0 = (str1Field.get())
        char0 = (char1Field.get())
       
        i=0
        count=0
        while(i<len(String0)):
            if(String0[i]==char0):
                count=count+1
            i=i+1
       
        resultField.insert(10, str(count))
       
if __name__ == "__main__" :

    gui = Tk()
    gui.configure(background = "light green")
    gui.title("occurrences of a character in a string")
    gui.geometry("525x260")
 
 
 
    Stringin = Label(gui, text = " given String", bg = "#00ffff")
    char = Label(gui, text = "given character", bg = "#00ffff")
    str1 = Label(gui, text = "String", bg = "light green")
    char1 = Label(gui, text = "character", bg = "light green")
   
    occurrenceslabel = Label(gui, text = "occurrences \n character",
    bg = "light green")
   
    result = Button(gui, text = "Result", fg = "Black",
    bg = "gray", command = occurrences)
    clearAllEntry = Button(gui, text = "Clear All", fg = "Black",
    bg = "Red", command = clearAll)

    str1Field = Entry(gui)
    char1Field = Entry(gui)
    resultField = Entry(gui)

Stringin.grid(row = 0, column = 1)
str1.grid(row = 1, column = 0)
str1Field.grid(row = 1, column = 1)
   
   
char.grid(row = 0, column = 4)
char1.grid(row = 1, column = 3)
char1Field.grid(row = 1, column = 4)
   
result.grid(row = 4, column = 2)
occurrenceslabel.grid(row = 5, column = 2)
resultField.grid(row = 6, column = 2)
clearAllEntry.grid(row = 12, column = 2)

gui.mainloop()

OUTPUT:




Write a Python script to sort (ascending and descending) a dictionary by key and value.

Slip 29 Q 2

CODE :


dict1 = {}
n=int (input('Enter a number or pair in dict :'))
for i in range(n):
    key=input('enter {0} key :'.format(i+1))
    value=input('enter value of {}:'.format(key))
    dict1[key]=value
   
sorted_result = dict(sorted(dict1.items()))
print("\nSorting key in alphabetically ascending order:-")
print(sorted_result)

sorted_result = dict(sorted(dict1.items(), reverse=True))
print("\nSorting Dictionary by Key in Descending Order:-")
print(sorted_result)


a = dict(sorted(dict1.items(), key=lambda x: x[1]))
print("\nsort dictionary by value Ascending:-")
print(a)

a = dict(sorted(dict1.items(), key=lambda x: x[1], reverse=True))
print("\nSort dictionary by value descending:-")
print(a)

OUTPUT:



Write a Python GUI program to calculate volume of Sphere by accepting radius as input.

Slip 29 Q 1

CODE :


from tkinter import *
from tkinter import messagebox
import math
def clearAll() :
    radiusField.delete(0, END)
    volumeField.delete(0, END)

   
def checkError() :
    if (radiusField.get() == "") :
        messagebox.showerror("Input Error")
        clearAll()
        return -1

def getvolume() :
    value = checkError()
    if value == -1 :
        return
    else :
        radius0 = int(radiusField.get())
        volume0=round((4/3)*math.pi*radius0*radius0*radius0,2)
       
        volumeField.insert(10, str(volume0))
       
if __name__ == "__main__" :

    gui = Tk()
    gui.configure(background = "light green")
    gui.title("volume of sphere")
    gui.geometry("425x200")
 
 
 
    Radiuslabel = Label(gui, text = "given Radius", bg = "#00ffff")
    volumelabel = Label(gui, text = "result volume", bg = "#00ffff")
    Radius1 = Label(gui, text = "radius", bg = "light green")
    volume1 = Label(gui, text = "volume", bg = "light green")
   
    result = Button(gui, text = "Result", fg = "Black",
    bg = "gray", command = getvolume)
    clearAllEntry = Button(gui, text = "Clear All", fg = "Black",
    bg = "Red", command = clearAll)

    radiusField = Entry(gui)
 
    volumeField = Entry(gui)

Radiuslabel.grid(row = 0, column = 1)
Radius1.grid(row = 1, column = 0)
radiusField.grid(row = 1, column = 1)
   
   
volumelabel.grid(row = 0, column = 4)
volume1.grid(row = 1, column = 3)
volumeField.grid(row = 1, column = 4)
   
result.grid(row = 4, column = 2)
clearAllEntry.grid(row = 12, column = 2)

gui.mainloop()


OUTPUT:



Write a Python program to accept two lists and merge the two lists into list of tuple.

Slip 28 Q 2

CODE :


list1 =[]
n=int(input('Enter number of elements in first list : '))
for i in range(n):
    value=int(input('enter {} value of list : '.format(i+1)))
    list1.append(value)

list2 =[]
n=int(input('Enter number of elements in second list : '))
for i in range(n):
    value=int(input('enter {} value of list : '.format(i+1)))
    list2.append(value)

print('list 1 : ',list1)
print('list 2 : ',list2)
tuple1=tuple(list1+list2)
print(tuple1)

OUTPUT:




Write a Python GUI program to create a list of Computer Science Courses using Tkinter module (use Listbox).

Slip 28 Q 1

CODE :


from tkinter import *

top = Tk()
top.title('Course')
top.geometry("300x250")
Lb1 = Listbox(top,fg='yellow',width=30,bg='gray',bd=1,activestyle='dotbox')
label=Label(top,text='Computer Science Course Listing').pack()
Lb1.insert(1, "Computer Programming")
Lb1.insert(2, "Information Science")
Lb1.insert(3, "Networking")
Lb1.insert(4, "Operating Systems")
Lb1.insert(5, "Artificial Intelligence")
Lb1.insert(6, "Information Technology")
Lb1.insert(7,'Information Security')
Lb1.insert(8, "Cyber Security")

Lb1.pack()
top.mainloop()

OUTPUT:



Write Python GUI program to accept a decimal number and convert and display it to binary, octal and hexadecimal number.

Slip 27 Q 2

CODE :

from tkinter import *
from tkinter import messagebox

def clearAll() :
    numberField.delete(0, END)
    binaryField.delete(0, END)
    octalField.delete(0, END)
    hexadecimalField.delete(0, END)

def checkError() :

    if (numberField.get() == "") :

        messagebox.showerror("Input Error")

        clearAll()
       
        return -1

def calculateAge() :

    value = checkError()

    if value == -1 :
        return
   
    else :
       
        number0 = int(numberField.get())
        binary=(bin(number0)[2:])
        octal =oct(number0)[2:]
        hexadecimal=hex(number0)[2:]

        binaryField.insert(10, str(binary))
        octalField.insert(10, str(octal))
        hexadecimalField.insert(10, str(hexadecimal))
   
if __name__ == "__main__" :

    gui = Tk()
    gui.configure(background = "light green")
    gui.title("decimal number converter")
    gui.geometry("400x200")
 
 
 
    number = Label(gui, text = "Give number", bg = "#00ffff")
    number1 = Label(gui, text = "number", bg = "light green")
    numberField = Entry(gui)

    result = Label(gui, text = "result", bg = "#00ffff")

    resultbutton = Button(gui, text = "Result button", fg = "Black",
    bg = "gray", command = calculateAge)

    resultbinary = Label(gui, text = "result binary", bg = "light green")
    resultoctal = Label(gui, text = "result cotal", bg = "light green")
    resulthexadecimal = Label(gui,text ="resulthexadecimal",bg = "light green")

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

    number.grid(row = 0, column = 1)
    number1.grid(row = 1, column = 1)
    numberField.grid(row = 2, column = 1)
   
    result.grid(row = 3, column = 1)
    resultbutton.grid(row = 4, column = 1)
   
    resultbinary.grid(row = 5, column = 0)
    binaryField.grid(row = 6, column = 0)
   
    resultoctal.grid(row = 5, column = 1)
    octalField.grid(row = 6, column = 1)
 
    resulthexadecimal.grid(row = 5, column = 2)
    hexadecimalField.grid(row = 6, column = 2)
 
    clearAllEntry.grid(row = 7, column = 1)

    gui.mainloop()

OUTPUT:



Write a Python program to unzip a list of tuples into individual lists.

Slip 27 Q 1

CODE :


l = [(1,2), (3,4), (8,9)]
print(list(zip(*l)))



OUTPUT:



Write Python GUI program which accepts a sentence from the user and alters it when a button is pressed. Every space should be replaced by *, case of all alphabets should be reversed, digits are replaced by?.

Slip 26 Q 2

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 occurrences() :
    value = checkError()
    if value == -1 :
        return
    else :
        String0 = (str1Field.get())
       
        newstr=''
        for char in String0:
            if char.isupper():
                char=char.lower()
                newstr+=char
            elif char.islower():
                char=char.upper()
                newstr+=char
            elif char==' ':
                char=char.replace(' ','*')
                newstr+=char
            elif char.isdigit():
                char=char.replace(char,'?')
                newstr+=char
            else:
                newstr+=char
       
        altersField.insert(10, str(newstr))
       
if __name__ == "__main__" :
    gui = Tk()
    gui.configure(background = "light green")
    gui.title("alters")
    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 = occurrences)
   
    alters = Label(gui, text = "alters 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()


OUTPUT:




Write an anonymous function to find area of square and rectangle.

Slip 26 Q 1

CODE :

area_square=lambda x: x*x       #area of square is a^2
side=int(input('Enter a side value of square : '))
print(area_square(side))

area_rectangle=lambda x,y:x*y   #area of rectangle is l*w
Length=int(input('Enter a Length value of rectangle : '))
Width=int(input('Enter a Width value of rectangle : '))
print(area_rectangle(Length,Width))

OUTPUT :




Write a Python script to Create a Class which Performs Basic Calculator Operations.

Slip 25 Q 2

CODE :



class Calculator:
    def __init__(self,num1,num2,operation):
        self.num1=num1
        self.num2=num2
        self.operation=operation
        if self.operation=='*':
            print('Multiplication of {} and {} is : '.format(num1,num2),
                self.num1*self.num2)
           
        elif self.operation=='/':
            print('division of {} and {} is : '.format(num1,num2),
                self.num1/self.num2)
           
        elif self.operation=='-':
            print('Subtraction of {} and {} is : '.format(num1,num2),
                self.num1/self.num2)
           
        elif self.operation=='+':
            print('Addition of {} and {} is : '.format(num1,num2),
                self.num1+self.num2)
           
num1=int(input('Enter 1st number : '))
operator1=input('ENTER A CALCULATOR OPERATOR FROM FOLLOWING : / , * , - ,  +\n')
num2=int(input('Enter 2st number : '))      
Calculator(num1,num2,operator1)



OUTPUT:





Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters.

Slip 25 Q 1

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)


OUTPUT:



Write Python GUI program which accepts a number n to displays each digit of number in words.

Slip 24 Q 2

CODE:


from tkinter import END, Button, Entry, Label, Tk


def printWord(N):
    i = 0
    length = len(N)
    while i < length:    
        printValue(N[i])
        i += 1
       
def printValue(digit):
    if digit == '0':
        wordField.insert(30,'ZERO ')
    elif digit == '1':
        wordField.insert(30,'ONE ')
    elif digit == '2':
        wordField.insert(30,'TWO ')
    elif digit=='3':
        wordField.insert(30,'THREE ')
    elif digit == '4':
        wordField.insert(30,'FOUR ')
    elif digit == '5':
        wordField.insert(30,'FIVE ')
    elif digit == '6':
        wordField.insert(30,'SIX ')
    elif digit == '7':
        wordField.insert(30,'SEVEN ')
    elif digit == '8':
        wordField.insert(30,'EIGHT ')
    elif digit == '9':
        wordField.insert(30,'NINE ')
       
def clearAll() :
    numberField.delete(0, END)
    wordField.delete(0, END)
   

def wordconvert():
   
    number0 = numberField.get()
    printWord(number0)

if __name__=="__main__" :
    gui = Tk()
    gui.configure(background = "light green")
    gui.title("decimal number converter")
    gui.geometry("300x125")
    number = Label(gui, text = "Give number", bg = "#00ffff")
    number1 = Label(gui, text = "number", bg = "light green")
    numberField = Entry(gui)
    result = Label(gui, text = "result", bg = "#00ffff")
    resultbutton = Button(gui, text = "Result button",fg = "Black",
    bg = "gray", command = wordconvert)
    numberinword = Label(gui, text ="number in word",bg ="light green")
    wordField = Entry(gui)
    clearAllEntry = Button(gui, text = "Clear All", fg ="Black",
    bg = "gray", command = clearAll)
   
    number.grid(row = 0, column = 1)
    number1.grid(row = 1, column = 1)
    numberField.grid(row = 2, column = 1)
    resultbutton.grid(row = 3, column = 1)
   
    result.grid(row = 0, column = 5)
    numberinword.grid(row = 1, column = 5)
    wordField.grid(row = 2, column = 5)
    clearAllEntry.grid(row = 3, column = 5)
    gui.mainloop()
   

OUTPUT:




Write a Java program to display given extension files from a specific directory on server machine.

 DOWNLOAD     SLIP14Q2 /** * STEPS TO RUN CODE * Step 01 compile the code * Step 02 run the code * Step 03 give a file directory locatio...