Merged Solutions
Merged Solutions
slip1a: Write a Python program to accept n numbers in list and remove duplicates from a list.
CODE:
unique_numbers = list(set(numbers))
OUTPUT:
slip1b: Write Python GUI program to take accept your birthdate and output your age when a button is
pressed.
CODE:
import tkinter as tk
def calculate_age():
try:
birthdate = entry.get()
today = datetime.today()
except ValueError:
window = tk.Tk()
window.title("Age Calculator")
label.pack(pady=10)
entry = tk.Entry(window)
entry.pack(pady=5)
button.pack(pady=10)
window.mainloop()
OUTPUT:
slip2a & slip24a & slip25a: Write a Python function that accepts a string and calculate the number of upper
case letters and lower case letters.
Expected Output:
CODE:
def count_case_letters(s):
upper_count = 0
lower_count = 0
for char in s:
if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1
count_case_letters(sample_string)
OUTPUT:
slip2b: Write Python GUI program to create a digital clock with Tkinter to display the time.
CODE:
import tkinter as tk
import time
def update_time():
current_time = time.strftime("%H:%M:%S")
clock_label.config(text=current_time)
clock_label.after(1000, update_time)
root = tk.Tk()
root.title("Digital Clock")
clock_label.pack(padx=20, pady=20)
update_time()
root.mainloop()
OUTPUT:
slip3a: Write a Python program to check if a given key already exists in a dictionary. If key exists
replace with another key/value pair.
CODE:
old_key = 'b'
new_key = 'd'
new_value = 4
if old_key in my_dict:
del my_dict[old_key]
my_dict[new_key] = new_value
else:
my_dict[new_key] = new_value
OUTPUT:
slip3b & slip10b: 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.
CODE:
class Student:
self.roll_no = roll_no
self.name = name
self.age = age
self.gender = gender
class Test(Student):
def total_marks(self):
return sum(self.marks)
OUTPUT:
slip4a: Write Python GUI program to create background with changing colors.
CODE:
import tkinter as tk
import random
def change_bg_color():
chosen_color = random.choice(colors)
root.config(bg=chosen_color)
root.after(1000, change_bg_color)
root = tk.Tk()
change_bg_color()
root.mainloop()
OUTPUT:
slip4b: 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).
CODE:
class Employee:
self.id = id
self.name = name
self.department = department
self.salary = salary
def display(self):
class Manager(Employee):
self.bonus = bonus
def display(self):
super().display()
print(f"Bonus: {self.bonus}")
def total_salary(self):
managers = []
for _ in range(n):
managers.append(manager)
max_manager = managers[0]
max_manager = manager
max_manager.display()
OUTPUT:
slip5a: 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.
CODE:
class SimpleString:
self.text = ""
def get_string(self):
def print_string(self):
print(self.text.upper())
string_obj = SimpleString()
string_obj.get_string()
string_obj.print_string()
OUTPUT:
slip5b: Write a python script to generate Fibonacci terms using generator function.
CODE:
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(term)
OUTPUT:
slip6a: Write python script using package to calculate area and volume of cube and sphere.
CODE:
import math
class Geometry:
@staticmethod
def cube_area(side):
return 6 * (side ** 2)
@staticmethod
def cube_volume(side):
return side ** 3
@staticmethod
def sphere_area(radius):
@staticmethod
def sphere_volume(radius):
cube_side = 3
sphere_radius = 4
OUTPUT:
slip6b: 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.
CODE:
import tkinter as tk
root = tk.Tk()
var_font = tk.BooleanVar()
var_bold = tk.BooleanVar()
var_size = tk.BooleanVar()
label.pack(pady=20)
check_font.pack()
check_bold.pack()
check_size.pack()
root.mainloop()
OUTPUT:
slip7a: Write Python class to perform addition of two complex numbers using binary + operator overloading.
CODE:
class ComplexNumber:
self.real = real
self.imaginary = imaginary
return f"{self.real} +
{self.imaginary}i" c1 = ComplexNumber(3,
2)
c2 = ComplexNumber(1, 7)
result = c1 + c2
print("Sum:", result)
OUTPUT:
slip7b: Write python GUI program to generate a random password with upper and lower case letters.
CODE:
import tkinter as tk
import random
import string
def generate_password(length):
root = tk.Tk()
length_label.pack(pady=10)
length_entry = tk.Entry(root)
length_entry.pack(pady=5)
generate_button.pack(pady=20)
password_entry.pack(pady=5)
root.mainloop()
OUTPUT:
slip8a & slip10a: Write a python script to find the repeated items of a tuple.
CODE:
my_tuple = (1, 2, 3, 4, 2, 5, 6, 1, 7, 8, 3)
item_counts = {}
if item in item_counts:
item_counts[item] += 1
else:
item_counts[item] = 1
OUTPUT:
slip8b & slip9b: 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.
CODE:
class SimpleString:
self.text = ""
def get_string(self):
def print_string(self):
print("Uppercase:", self.text.upper())
def reverse_and_lower(self):
string_obj = SimpleString()
string_obj.get_string()
string_obj.print_string()
string_obj.reverse_and_lower()
OUTPUT:
slip9a: Write a Python script using class to reverse a string word by word.
CODE:
class StringReverser:
self.text = text
def set_text(self):
def reverse_words(self):
print("Reversed:", reversed_words)
reverser = StringReverser()
reverser.set_text()
reverser.reverse_words()
OUTPUT:
slip11a & slip21a: 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.
CODE:
class Rectangle:
self.length = length
self.width = width
def area(self):
def perimeter(self):
OUTPUT:
Slip11b & slip 25b: Write a Python script to Create a Class which Performs Basic Calculator Operations.
CODE:
class Calculator:
return a + b
return a - b
return a * b
if b == 0:
return a / b
calc = Calculator()
a = 10
b=5
OUTPUT:
slip12a: Write a Python GUI program to create a label and change the label font style (font name, bold, size)
using tkinter module.
CODE:
import tkinter as tk
font
label.config(font=new_font)
root = tk.Tk()
label.pack(pady=20)
menu = tk.Menu(root)
font_options = [
menu.add_cascade(label="Fonts", menu=font_menu)
root.config(menu=menu)
root.mainloop()
OUTPUT:
slip12b & slip19b & slip29b: Write a python program to count repeated
CODE:
sample_string = 'thequickbrownfoxjumpsoverthelazydog'
char_count = {}
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
if count > 1:
OUTPUT:
slip13a & slip14a: Write a Python program to input a positive integer. Display correct message for
correct and incorrect input. (Use Exception Handling)
CODE:
def get_positive_integer():
try:
except ValueError as e:
get_positive_integer()
OUTPUT:
slip 13b: Write a program to implement the concept of queue using list.
CODE:
queue = []
def enqueue(item):
queue.append(item)
def dequeue():
if not is_empty():
return queue.pop(0)
else:
def is_empty():
return len(queue) == 0
enqueue(1)
enqueue(2)
enqueue(3)
OUTPUT:
Slip14b & slip20b: Write a Python script to generate and print a dictionary which contains a number
(between 1 and n) in the form(x,x*x).
Sample Dictionary (n=5) Expected Output: {1:1, 2:4, 3:9, 4:16, 5:25}
CODE:
def generate_square_dict(n):
n=5
result_dict = generate_square_dict(n)
print(result_dict)
OUTPUT:
slip15a: 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.
CODE:
class Student:
self.student_name = student_name
self.marks = marks
self.student_name = new_name
self.marks = new_marks
def print_attributes(self):
print(f"Marks: {self.marks}")
print("Original values:")
student.print_attributes()
student.modify_attributes("Bob", 90)
print("\nModified values:")
student.print_attributes()
OUTPUT:
slip15b: Write a python program to accept string and remove the characters which have odd index values of
given string using user defined function.
CODE:
def remove_odd_index_chars(s):
return s[::2]
result = remove_odd_index_chars(user_input)
OUTPUT:
slip16a & slip 18a: 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
CODE:
for number in a:
if number < 5:
print(number)
OUTPUT:
Slip 16b & slip21b: Write a Python program to convert a tuple of string values to a tuple of
CODE:
OUTPUT:
slip17a & slip 20a & slip29a: Write a python program to create a class Circle and Compute the Area and
the circumferences of the circle.(use parameterized constructor)
CODE:
import math
class Circle:
self.radius = radius
def area(self):
def circumference(self):
circle = Circle(radius=5)
OUTPUT:
slip17b & slip18b: 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.
CODE:
class Person:
self.name = name
self.address = address
def display_info(self):
print(f"Name: {self.name}")
print(f"Address: {self.address}")
class Employee(Person):
self.staff_id = staff_id
self.salary = salary
def display_info(self):
super().display_info()
print(f"Salary: $
{self.salary:.2f}")
def main():
employees = []
for _ in range(n):
employees.append(employee)
print("\nEmployee Details:")
emp.display_info()
print("-" * 30)
main()
OUTPUT:
slip19a & slip28a: Write a Python GUI program to create a list of Computer Science Courses using
Tkinter module (use Listbox).
CODE:
import tkinter as tk
def display_selected_course(event):
selected_course = course_listbox.get(course_listbox.curselection())
root = tk.Tk()
courses = [
"Introduction to
Programming", "Data
Structures", "Algorithms",
"Database Management
"Operating Systems",
"Software Engineering",
"Web Development",
"Machine Learning",
"Artificial Intelligence"
course_listbox.pack(pady=20)
course_listbox.insert(tk.END, course)
selection_label.pack(pady=10)
course_listbox.bind('<<ListboxSelect>>', display_selected_course)
root.mainloop()
OUTPUT:
slip22a: Write a python class to accept a string and number n from user and display n repetition of strings by
overloading * operator.
CODE:
class Repeater:
self.string = string
return self.string * n
else:
def main():
repeater = Repeater(user_string)
try:
print(f"Result: {result}")
except ValueError as e:
print(e)
main()
OUTPUT:
slip22b & slip26b: Write a python script to implement bubble sort using list
CODE:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
def main():
bubble_sort(arr)
main()
OUTPUT:
slip23a: Write a Python GUI program to create a label and change the label font style (font name, bold, size)
using tkinter module.
CODE:
import tkinter as tk
font
label.config(font=new_font)
root = tk.Tk()
label.pack(pady=20)
menu = tk.Menu(root)
font_options = [
menu.add_cascade(label="Fonts", menu=font_menu)
root.config(menu=menu)
root.mainloop()
OUTPUT:
slip23b & slip24b: Create a class circles having members radius. Use operator overloading to add the
radius of two circle objects. Also display the area of circle.
CODE:
import math
class Circle:
self.radius = radius
def area(self):
return f"Circle(radius={self.radius:.2f},
circle1 = Circle(radius1)
circle2 = Circle(radius2)
print(circle1)
print(circle2)
print(circle3)
main()
OUTPUT:
slip26a: Write an anonymous function to find area of square and rectangle.
CODE:
side = 4
length = 5
width = 3
print("Area of rectangle with length", length, "and width", width, "is:", area_rectangle(length, width))
OUTPUT:
slip27a: Write a Python program to unzip a list of tuples into individual lists.
CODE:
list1 = list(list1)
list2 = list(list2)
OUTPUT:
Slip27b & 28b: Write a Python program to accept two lists and merge the two lists into list of tuple.
CODE:
def main():
main()
OUTPUT:
slip30a: Write a Python GUI program to accept a string and a character from user and count the occurrences
of a character in a string.
CODE:
import tkinter as tk
def count_character():
input_string = entry_string.get()
input_char = entry_char.get()
if len(input_char) != 1:
return
count = input_string.count(input_char)
root = tk.Tk()
root.title("Character Counter")
label_string.pack(pady=5)
entry_string.pack(pady=5)
label_char.pack(pady=5)
entry_char.pack(pady=5)
count_button.pack(pady=20)
root.mainloop()
OUTPUT:
slip30b: Python Program to Create a Class in which One Method Accepts a String from the User and
Another method Prints it. Define a class named Country which has a method called print Nationality. Define
subclass named state from Country which has a mehtod called printState. Write a method to print state,
country and nationality.
CODE:
class Country:
self.nationality = ""
def input_nationality(self):
def print_nationality(self):
print(f"Nationality: {self.nationality}")
class State(Country):
super(). init ()
self.state = ""
def input_state(self):
def print_state(self):
print(f"State: {self.state}")
print(f"Country: {self.nationality}")
print(f"Nationality: {self.nationality}")
my_location = State()
my_location.input_nationality()
my_location.input_state()
my_location.print_state()
OUTPUT:
JAVA PRACTICAL SOLN
slip1a & 7a & slip14a: Write a ‘java’ program to display characters from ‘A’ to ‘Z’.
CODE:
public class Slip1A{
public static void main(String[] args){
for(char i='A';i<='Z';i++){
System.out.println(i);
}
}
}
slip1b & slip10b & slip15b: Write a ‘java’ program to copy only non-numeric data from one file to another
file.
CODE:
import java.io.*;
//import java.io.BufferedReader;
//import java.io.FileReader;
//import java.io.IOException;
try{
File infile = new File("C:\\Users\\DELL\\Documents\\java\\old.txt");
File outfile = new File("C:\\Users\\DELL\\Documents\\java\\output.txt");
String str;
byte[] buffer = new byte[1024];
int length;
}
}
slip2a & slip10a: Write a java program to display all the vowels from a given string.
CODE:
public class Slip2A {
public static void main(String[] args) {
String str = "hello world";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
System.out.println("Vowels in string: "+ch);
}
}
}
}
slip2b & slip19b & slip26a & slip29a: Write a Java program to display ASCII values of the characters from
a file.
CODE:
import java.util.*;
import java.io.*;
class Slip26a{
public static void main(String[] agrs) throws IOException{
char ch;
FileReader fr = new FileReader("old.txt");
int c;
while((c = fr.read()) != -1){
ch = (char)c;
if(Character.isDigit(ch) == false && (Character.isSpaceChar(c) == false)){
System.out.println("ASCII " +ch+ ":" +c);
}
}
fr.close();
}
}
slip3a: Write a ‘java’ program to check whether given number is Armstrong or not.
(Use static keyword)
CODE:
public class Slip3A{
public static void main(String[] args) {
int num = 153; // Specified number to check
int temp=num;
int rem,sum=0;
while(num>0){
rem=num%10;
num=num/10;
sum=sum+rem*rem*rem;
}
// Check if the number is an Armstrong number
if (temp==sum) {
System.out.println(" is an Armstrong number.");
} else {
System.out.println(" is not an Armstrong number.");
}
}
}
slip3b: Define an abstract class Shape with abstract methods area () and volume (). Derive
abstract class Shape into two classes Cone and Cylinder. Write a java Program
to calculate area and volume of Cone and Cylinder. (Use Super Keyword.)
CODE:
abstract class Shape {
// Abstract methods for calculating area and volume
abstract double area();
abstract double volume();
}
while(lit.hasPrevious()){
System.out.println(" " +lit.previous());
}
}
}
slip5a: Write a java program to display following pattern:
5
45
345
2345
12345
CODE:
public class NumberPattern {
public static void main(String[] args) {
// Display numbers in the specified pattern
for (int i = 5; i >= 1; i--) {
for (int j = i; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
slip5b & slip24b: Write a java program to accept list of file names through command line. Delete the
files having extension .txt. Display name, location and size of remaining files.
CODE:
import java.io.*;
class Slip5b{
public static void main(String[] args){
for(int i=0; i<args.length; i++){
File file = new File(args[i]);
if(file.isFile()){
String name = file.getName();
if(name.endsWith(".txt")){
file.delete();
System.out.println("file is deleted successfully!" +file);
}
else{
System.out.println("file name: " +name + "\nfile location: " +file.getAbsolutePath() + "\nfile size: "
+file.length() +"bytes");
}
}
else{
System.out.println(args[i] + "is not a file");
}
}
}
}
slip6a: Write a java program to accept a number from user, if it zero then throw user
defined Exception “Number Is Zero”, otherwise calculate the sum of first and last digit
of that number. (Use static keyword).
CODE:
import java.util.Scanner;
// Static method to calculate the sum of the first and last digit
public static int sumOfFirstAndLastDigit(int number) {
int lastDigit = number % 10; // Get last digit
int firstDigit = Character.getNumericValue(Integer.toString(number).charAt(0)); // Get first digit
return firstDigit + lastDigit; // Return the sum
}
try {
// Check if the number is zero
if (num == 0) {
throw new NumberIsZeroException("Number Is Zero");
}
// Calculate and display the sum of the first and last digit
int sum = sumOfFirstAndLastDigit(num);
System.out.println("Sum of the first and last digit: " + sum);
} catch (NumberIsZeroException e) {
System.out.println(e.getMessage()); // Display the exception message
} finally {
// Close the scanner
scanner.close();
}
}
}
slip6b & Slip7b: Write a java program to display transpose of a given matrix.
CODE:
import java.util.Scanner;
interface Shape {
double area();
}
scanner.close();
}
}
Slip8b: Write a java program to display the files having extension .txt from a given
directory.
CODE:
import java.io.*;
class Slip8b{
public static void main(String[] args){
File file = new File("C:\\Users\\DELL\\Documents\\java");
File [] fl = file.listFiles((d, f)-> f.toLowerCase().endsWith(".txt"));
for(File f: fl){
System.out.println(f.getName());
}
}
}
Slip9a & slip16a: Write a java Program to display following pattern:
1
01
010
1010
CODE:
public class PatternDisplay {
public static void main(String[] args) {
int rows = 4; // Number of rows in the pattern
try {
validatePAN(pan);
validateMobile(mobile);
System.out.println("Valid PAN number: " + pan);
System.out.println("Valid Mobile number: " + mobile);
} catch (InvalidDataException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
class Slip13a{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("enter no. of elements: ");
int n = sc.nextInt();
ArrayList<String> list = new ArrayList<>();
System.out.println("enter the elements of array list collection: ");
for(int i = 0; i<n; i++){
String ele = sc.next();
list.add(ele);
}
}
}
slip13b & slip17b & slip21b: Write a java program that asks the user name, and then greets the user by
name Before outputting the user's name, convert it to upper case letters. For example, if
the user's name is Raj, then the program should respond "Hello, RAJ, nice to meet
you!".
CODE:
import java.util.Scanner;
scanner.close();
}
}
slip15a & slip24a: Write a java program to search given name into the array, if it is found then display
its index otherwise display appropriate message.
CODE:
import java.util.Scanner;
if (found) {
System.out.println("Name found at index: " + index);
} else {
System.out.println("Name not found in the array.");
}
scanner.close();
}
}
slip16b & slip18b & slip29b: Write a java program to copy the data from one file into another file, while
copying change the case of characters in target file and replaces all digits by ‘*’ symbol.
CODE:
import java.io.*;
class Slip18b{
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("old.txt");
FileWriter fw = new FileWriter("new.txt");
int c;
scanner.close();
}
}
Slip20a: Write a java program using AWT to create a Frame with title “TYBBACA”,
background color RED. If user clicks on close button then frame should close.
CODE:
import java.awt.*;
import java.awt.event.*;
setVisible(true);
}
class Slip21a{
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("old.txt");
FileWriter fw = new FileWriter("new2.txt");
try{
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
String s = sc.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer = buffer.reverse();
String res = buffer.toString();
fw.write(res);
}
}
catch(Exception e){}
fr.close();
fw.close();
}
}
Slip22a: Write a Java program to calculate factorial of a number using recursion.
CODE:
import java.util.Scanner;
class Slip22b{
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
System.out.println("1. create a file \n2. rename a file \n3. delete a file \n4. display file path");
System.out.println("enter a file name: ");
switch(ch){
case 1:
if(file.createNewFile()){
System.out.println("file created: " +file.getName());
}
else{
System.out.println("file already exists");
}
break;
case 2:
System.out.print("enter new file name: ");
String nf = sc.nextLine();
File nf1 = new File(nf);
if(file.renameTo(nf1)){
System.out.println("file renamed");
}
else{
System.out.println("file can't be renamed");
}
break;
case 3:
if(file.delete()){
System.out.println("delete the file: " +file.getName());
}
else{
System.out.println("failed to delete the file");
}
break;
case 4:
System.out.println("file location: " +file.getAbsolutePath());
break;
default:
System.out.println("please choose the correct option");
break;
}
}
}
Slip23a: Write a java program to check whether given file is hidden or not. If not then
display its path, otherwise display appropriate message.
CODE:
slip23a:
import java.io.*;
import java.util.*;
try{
System.out.print("enter file name: ");
String str = sc.nextLine();
File file = new File(str);
if(file.isHidden()){
System.out.println("file is hidden");
}
else{
System.out.println("file location: " +file.getAbsolutePath());
}
}
catch(Exception e){}
}
}
Slip25a: Write a java program to check whether given string is palindrome or not.
CODE:
import java.util.Scanner;
scanner.close();
}
2. CubeSeries.java:
package Series;
3. SquareSeries.java:
package Series;
scanner.close();
}
}
public EmployeeDetails() {
frame = new JFrame("Employee Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 400);
frame.setLayout(new BorderLayout());
// Panel for input fields
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new GridLayout(4, 2));
inputPanel.add(new JLabel("Salary:"));
salaryField = new JTextField();
inputPanel.add(salaryField);
frame.add(inputPanel, BorderLayout.NORTH);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addEmployee();
}
});
frame.setVisible(true);
}
import java.util.Scanner;
scanner.close();
}