Slip Programs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Slip 1:

Design a class Employee with data members: name, department and salary. Create suitable
methods for reading and printing employee information

class Employee:

def read_employee(self):

self.name = input("Enter employee name: ")

self.department = input("Enter department: ")

self.salary = float(input("Enter salary: "))

def print_employee(self):

print("Employee Information")

print("Name: ", self.name)

print("Department: ", self.department)

print("Salary: ", self.salary)

employee1 = Employee()

employee1.read_employee()

employee1.print_employee()
Slip 2:

Write a python program to calculate factorial of given number using function

def calculate_factorial(number):

if number == 0 or number == 1:

return 1

else:

return number * calculate_factorial(number - 1)

num = int(input("Enter a number to calculate its factorial: "))

if num < 0:

print("Factorial is not defined for negative numbers.")

else:

result = calculate_factorial(num)

print(f"The factorial of {num} is: {result}")


Slip 3:

Write a python program to read contents of first.txt file and write same content in
second.txt file

def copy_file_contents(input_file, output_file):

try:

with open(input_file, "r") as file1:

file1_content = file1.read()

with open(output_file, "w") as file2:

file2.write(file1_content)

print(f"Contents of {input_file} copied to {output_file}


successfully.")

except FileNotFoundError:

print("Error: One or both files not found.")

input_file_name = "first.txt"

output_file_name = "second.txt"

copy_file_contents(input_file_name, output_file_name)
Slip 4:

Write a python program to print Fibonacci series up to n terms

def print_fibonacci(n):

if n <= 0:

print("Please enter a positive integer for the number


ofterms.")

num1 = 0

num2 = 1

next_number = num2

count = 1

while count <= n:

print(next_number, end=" ")

count += 1

num1, num2 = num2, next_number

next_number = num1 + num2

print()

print_fibonacci(int(input("Enter the number of terms for the


Fibonacci series: ")))
Slip 5:

Write a program to input any two tuples and interchange the tuple variable.

list1 = []

for i in range(1, 4):

num = int(input("Enter data for 1st tuple: "))

list1.append(num)

tup1 = tuple(list1)

list2 = []

for i in range(1, 4):

num = int(input("Enter data for 2nd tuple: "))

list2.append(num)

tup2 = tuple(list2)

tup1, tup2 = tup2, tup1

print("Tuple 1: ", tup1, "\nTuple 2: ", tup2)


Slip 6:

Design a python program to calculate area of triangle and circle and print the result

import math

def calculate_triangle_area(base, height):

print(0.5 * base * height)

def calculate_circle_area(radius):

print(math.pi * radius**2)

base_tri = float(input("Enter the base of the triangle: "))

height_tri = float(input("Enter the height of the triangle: "))

# Input for the circle


radius_circle = float(input("Enter the radius of the circle: "))

# Calculate areas
calculate_triangle_area(base_tri, height_tri)

calculate_circle_area(radius_circle)
Slip 7:

Design a python program which will throw exception if the value entered by user is
less than zero

while True:

try:

user_input = int(input("Enter a positive value: "))

if user_input < 0:

raise ValueError("Error: Negative value is not


allowed.")

else:

print("You entered a positive value: ", user_input)

break

except ValueError as e:

print(e)

Slip 8:

Design a python program to create a class EMPLOYEE with ID and NAME and display its contents

class Employee:

def __init__(self, employee_id, employee_name):

self.id = employee_id

self.name = employee_name

def display_employee_data(self):

print("Employee ID:", self.id)

print("Employee NAME:", self.name)

employee1 = Employee("E001", "EMP 1")

employee1.display_employee_data()
Slip 9:

Design a program to importing a module for addition and subtractions of two numbers

Slip 10:

Design a program illustrating use of user define package in python

Root_folder/
├── Calculator/
│ ├── __init__.py
│ ├── module.py
└── main.py

Calculator/module.py

def addition(a, b):


return a + b
def subtract(a, b):
return a – b

Calculator/main.py

from Calculator import module as m

print(m.addition(90, 10))
print(m.subtract(20, 10))
Slip 11:

Design a program to open a file in write mode and append some content at the end of file

def append_to_file(file_name, content):


with open(file_name, "a") as file:
file.write(content)
print("Content appended successfully.")

file_name = "example.txt"
content_to_append = "\nThis is new content to append."

append_to_file(file_name, content_to_append)
Slip 12:

Design a python code to count frequency of each character in a given file.

def count_character_frequency(file_name):
try:
with open(file_name, "r") as file:
content = file.read()
char_frequency = {}
for char in content:
if char.isalpha():
char = char.lower()
char_frequency[char] =
char_frequency.get(char, 0) + 1
print("Character frequencies:")
for char, frequency in char_frequency.items():
print(f"{char}: {frequency}")

except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

file_name = "example.txt"
count_character_frequency(file_name)
Slip 13:

Design a class student with data members; Name, roll number address. Create suitable
method for reading and printing student’s details.

class Student:
def read_student_data(self):
self.name = input("Enter student name: ")
self.roll_number = input("Enter roll number: ")
self.address = input("Enter address: ")

def print_student_data(self):
print("Student Details:")
print("Name:", self.name)
print("Roll Number:", self.roll_number)
print("Address:", self.address)

student1 = Student()
student1.read_student_data()
student1.print_student_data()
Slip 14:

Create a parent class named Animals and a child class Herbivorous which will extend the
class Animal. In the child class Herbivorous over side the method feed( ) Create an object

class Animals:
def feed(self):
print("Generic feeding method.")

class Herbivorous(Animals):
def feed(self, diet):
print(f"Feeding with a herbivorous diet: {diet}.")

herbivorous_animal = Herbivorous()
herbivorous_animal.feed("Grass")
Slip 15:

Design a python program using module, show how to write and use module by importing
it.

Calculator.py

def add(x, y):


return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
return "Cannot divide by zero"

main.py
import calculator as c
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

sum_result = c.add(num1, num2)


difference_result = c.subtract(num1, num2)
product_result = c.multiply(num1, num2)
division_result = c.divide(num1, num2)

print(f"Sum: {sum_result}")
print(f"Difference: {difference_result}")
print(f"Product: {product_result}")
print(f"Division: {division_result}")
Slip 16:

Design a program illustrating use of user defined package in python.

Root_folder/
├── Calculator/
│ ├── __init__.py
│ ├── module.py
└── main.py

Calculator/module.py

def addition(a, b):


return a + b
def subtract(a, b):
return a – b

Calculator/main.py

from Calculator import module as m

print(m.addition(90, 10))
print(m.subtract(20, 10))
Slip 17:

Design a program to create class student with Roll no. and Name and display its contents

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

def display_student_info(self):
print("Student Details:")
print("Roll No:", self.roll_no)
print("Name:", self.name)

student1 = Student("93", "Student Name")


student1.display_student_info()

Slip 18:

Design a program to implement concept of inheritance in python.

class Animal:
def speak(self):
print("Animal Speaking")

class Dog(Animal):
def bark(self):
print("Dog Barking")

d = Dog()
d.bark()
d.speak()
Slip 19:

Write a python program that takes a number and checks whether it is palindrome or not

def is_palindrome(string):
str_repr = str(string)
return str_repr == str_repr[::-1]

user_input = input("Enter a string: ")

if is_palindrome(user_input):
print(f"{user_input} is a palindrome.")
else:
print(f"{user_input} is not a palindrome.")

Slip 20:

Write a python program to create a tuple and find maximum and minimum number from it

list1 = []
for i in range(1, 6):
num = int(input("Enter number: "))
list1.append(num)

tup = tuple(list1)
print("Max number in tuple: ", max(tup))
Slip 21:

Write a python program to check for ZeroDivisionError Exception

def divide_numbers(num1, num2):


try:
result = num1 / num2
print(f"The result of {num1} / {num2} is: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

try:
number1 = float(input("Enter the numerator: "))
number2 = float(input("Enter the denominator: "))
divide_numbers(number1, number2)
except ValueError:
print("Error: Please enter valid numeric values.")
Slip 22:

Write a python function that takes a number as parameter and check the number is prime or not.

def is_prime(number):
if number < 2:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True

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

if is_prime(user_number):
print(f"{user_number} is a prime number.")
else:
print(f"{user_number} is not a prime number.")

Slip 23:

Write a python program to calculate sum of digit of given number using function

def sum_of_digits(number):
num_str = str(number)
digit_sum = sum(int(digit) for digit in num_str)
return digit_sum

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


result = sum_of_digits(user_number)
print(f"The sum of digits of {user_number} is: {result}")
Slip 24, 26:

Create a parent class named Animal and a child class Herbivorous which will extend the class
Animal.in the child class Herbivorous over side the method feed() create an object

class Animals:
def feed(self):
print("Generic feeding method.")

class Herbivorous(Animals):
def feed(self, diet):
print(f"Feeding with a herbivorous diet: {diet}.")

herbivorous_animal = Herbivorous()
herbivorous_animal.feed("Grass")
Slip 25:

Write a python program to create a class ‘degree’ having a method ‘getdegree’ that prints “I got
degree”. It has two subclasses namely ‘Undergraduate’ and ‘Postgraduates’ each having a method
with the same name that prints “I am an undergraduate” and “I am a postgraduate” respectively.
Call the method by creating object of each of the three classes

class Degree:
def get_degree(self):
print("I got a degree.")

class Undergraduate(Degree):
def get_degree(self):
print("I am an undergraduate.")

class Postgraduate(Degree):
def get_degree(self):
print("I am a postgraduate.")

degree_holder = Degree()
undergraduate_student = Undergraduate()
postgraduate_student = Postgraduate()

degree_holder.get_degree()
undergraduate_student.get_degree()
postgraduate_student.get_degree()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy