0% found this document useful (0 votes)
4 views

python231827

The document contains a series of Python programs demonstrating various programming concepts including control statements, loops, to-do list management, class creation, and inheritance. Each program is menu-driven and allows user interaction to showcase functionalities such as checking digits, calculating salaries, and managing tasks. The document also includes outputs for each program, illustrating the expected results of the operations performed.

Uploaded by

samsiphonejp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

python231827

The document contains a series of Python programs demonstrating various programming concepts including control statements, loops, to-do list management, class creation, and inheritance. Each program is menu-driven and allows user interaction to showcase functionalities such as checking digits, calculating salaries, and managing tasks. The document also includes outputs for each program, illustrating the expected results of the operations performed.

Uploaded by

samsiphonejp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Register Number:231827

Date: 12-11-2024
Program 1:Menu driven program to demonstrate various forms of if statements in Python
---------------------------------------------------------------------------------------------------------------------
#Python program to demonstrate various control statements
def check_digit():
num=input("enter a number:")
if num.isdigit():
print(f"{num} is a digit.")
#function to demonstrate if else statement
def check_max():
num1=int(input("Enter the first number:"))
num2=int(input("Enter the second number:"))
if num1>num2:
print(f"{num1} is greater")
else:
print(f"{num2} is greater")
#function to demonstrate if elif else statement
def categorize_num():
num=int(input("Enter a number: "))
if num>0:
print(f"{num} is positive")
elif num<0:
print(f"{num} is negative")
else:
print(f"{num} is zero")
#function to demonstrate nested if
def check_age():
age=int(input("Enter a number:"))
if age>=18:
if age>=60:
print("You are a senior citizen")
else:
print("You are an adult")
else:
print("You are a minor.")
#menu driven program with if statement example
def menu():
while True:
print("\n--If Statements--")
print("1.Check digit(simple if).")
print("2.Check maximum(if else).")
print("3.Categorize number(if-elif-else).")
print("4.age category(nested if).")
print("5.Exit.")

choice=int(input("Enter your choice(1-5): "))


if choice==1:
print (check_digit())
elif choice==2:
print (check_max())

elif choice==3:
print (categorize_num())
elif choice==4:
print (check_age())
elif choice==5:
print("Thank you!!")
break
else:
print("Invalid choice.Enter a valid number.")

menu()

Output:
--If Statements--
1.Check digit(simple if).
2.Check maximum(if else).
3.Categorize number(if-elif-else).
4.age category(nested if).
5.Exit.
Enter your choice(1-5): 1
enter a number:12
12 is a digit.
None

--If Statements--
1.Check digit(simple if).
2.Check maximum(if else).
3.Categorize number(if-elif-else).
4.age category(nested if).
5.Exit.
Enter your choice(1-5): 2
Enter the first number:45
Enter the second number:30
45 is greater
None

--If Statements--
1.Check digit(simple if).
2.Check maximum(if else).
3.Categorize number(if-elif-else).
4.age category(nested if).
5.Exit.
Enter your choice(1-5): 3
Enter a number: 34
34 is positive
None

--If Statements--
1.Check digit(simple if).
2.Check maximum(if else).
3.Categorize number(if-elif-else).
4.age category(nested if).
5.Exit.
Enter your choice(1-5): 4
Enter a number:24
You are an adult
None

--If Statements--
1.Check digit(simple if).
2.Check maximum(if else).
3.Categorize number(if-elif-else).
4.age category(nested if).
5.Exit.
Enter your choice(1-5): 5
Thank you!!

Register Number:231827
Date: 12-11-2024
Program 2: Menu driven program to demonstrate various looping statements in Python
—-----------------------------------------------------------------------------------------------------------------
# Menu-driven program to demonstrate various looping statements in Python
# For loop
def print_numbers():
limit = int(input("Enter the limit number till where the numbers are to be printed: "))
for i in range(1, limit + 1):
print(i, end=" ")
print()

# While loop
def print_square():
number = int(input("Enter the number to get its square: "))
i=1
while i <= number:
print(f"Square of {i} is {i*i}")
i += 1

# Handling list and for loop


def display_list_items():
fruits = ["apple", "mango", "banana", "cherry", "date"]
print("Available fruits:")
for fruit in fruits:
print(fruit)

# Break statement in loop


def break_example():
while True:
num = int(input("Enter a number (or -1 to stop): "))
if num == -1:
print("Terminating the loop with break")
break
else:
print(f"You have entered: {num}")

# Continue statement in loop


def continue_example():
for i in range(1, 11):
if i % 2 == 0:
continue
print(f"odd number:{i}")
def main():
while True:
print("\nMenu:")
print("1. Print numbers using for loop")
print("2. Print square of numbers using while loop")
print("3. Display list items using for loop")
print("4. Demonstrate break statement in loop")
print("5. Demonstrate continue statement in loop")
print("6. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
print_numbers()
elif choice == 2:
print_square()
elif choice == 3:
display_list_items()
elif choice == 4:
break_example()
elif choice == 5:
continue_example()
elif choice == 6:
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")

main()

Output:

Menu:
1. Print numbers using for loop
2. Print square of numbers using while loop
3. Display list items using for loop
4. Demonstrate break statement in loop
5. Demonstrate continue statement in loop
6. Exit
Enter your choice: 1
Enter the limit number till where the numbers are to be printed: 2
12

Menu:
1. Print numbers using for loop
2. Print square of numbers using while loop
3. Display list items using for loop
4. Demonstrate break statement in loop
5. Demonstrate continue statement in loop
6. Exit
Enter your choice: 2
Enter the number to get its square: 5
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25

Menu:
1. Print numbers using for loop
2. Print square of numbers using while loop
3. Display list items using for loop
4. Demonstrate break statement in loop
5. Demonstrate continue statement in loop
6. Exit
Enter your choice: 3
Available fruits:
apple
mango
banana
cherry
date

Menu:
1. Print numbers using for loop
2. Print square of numbers using while loop
3. Display list items using for loop
4. Demonstrate break statement in loop
5. Demonstrate continue statement in loop
6. Exit
Enter your choice: 4
Enter a number (or -1 to stop): 3
You have entered: 3
Enter a number (or -1 to stop): -1
Terminating the loop with break

Menu:
1. Print numbers using for loop
2. Print square of numbers using while loop
3. Display list items using for loop
4. Demonstrate break statement in loop
5. Demonstrate continue statement in loop
6. Exit
Enter your choice: 5
odd number:1
odd number:3
odd number:5
odd number:7
odd number:9

Menu:
1. Print numbers using for loop
2. Print square of numbers using while loop
3. Display list items using for loop
4. Demonstrate break statement in loop
5. Demonstrate continue statement in loop
6. Exit
Enter your choice: 6
Exiting program.
Register Number:231827
Date: 12-11-2024
Program 3: Menu driven program to create and operate a to-do list using lists
------------------------------------------------------------------------------------------------------------------
def add_task(todo_list,task):
"""Add a task to the to-do list"""
todo_list.append(task)
print(f"Task '{task}' added!")

def view_tasks(todo_list):
"""View all the tasks in the to-do list"""
if not todo_list:
print("No tasks in the to-do list")
else:
print("To-do list:")
for i,task in enumerate(todo_list,1):
print(f"{i}.{task}")

def remove_task(todo_list,task_number):
"""Remove task from todo_list by its number"""
if 0<task_number<=len(todo_list):
removed_task=todo_list.pop(task_number-1)
print(f"task '{removed_task}' removed")
else:
print("Invalid task number")

todo_list=[]
while True:
print("\n1.Add task\n2.View the task\n3.Remove the task\n4.Exit")

choice=int(input("Enter your choice(1-5): "))


if choice==1:
task=input("Enter a task:")
add_task(todo_list,task)
elif choice==2:
view_tasks(todo_list)
elif choice==3:
task_number=int(input("Enter remove task:"))
remove_task(todo_list,task_number)
elif choice==4:
print("Thank you!!")
break
else:
print("Invalid choice.Enter a valid number.")

Output:
1.Add task
2.View the task
3.Remove the task
4.Exit
Enter your choice(1-5): 1
Enter a task: buy butter

Task 'buy butter' added!

1.Add task
2.View the task
3.Remove the task
4.Exit

Enter your choice(1-5): 1


Enter a task: place order

Task 'place order' added!

1.Add task
2.View the task
3.Remove the task
4.Exit

Enter your choice(1-5): 2

To-do list:
1.buy butter
2.place order

1.Add task
2.View the task
3.Remove the task
4.Exit

Enter your choice(1-5): 3


Enter remove task: 2

task 'place order' removed

1.Add task
2.View the task
3.Remove the task
4.Exit

Enter your choice(1-5): 4

Thank you!!

Register Number:231827
Date: 12-11-2024
Program 4: Program to create a Student class(Regno, Name, M1,M2,M3,Total) and
instantiate objects
—------------------------------------------------------------------------------------------------------------------
class Student():
Regno=0
name=" "
mks1=0
mks2=0
mks3=0
def accept(self):
self.Regno=int(input("Enter the register number"))
self.name=input("Enter the name")
self.mks1=int(input("Enter the english"))
self.mks2=int(input("Enter the maths"))
self.mks3=int(input("Enter the science"))

def cal(self):
self.tot=self.mks1+self.mks2+self.mks3
self.avg=self.tot/3

def dis(self):
print("Register number: ",self.Regno)
print("Name: ",self.name)
print("Marks 1: ",self.mks1)
print("Marks 2: ",self.mks2)
print("Marks 3: ",self.mks3)
print("Total: ",self.tot)
print("Average: ",self.avg)
stu=Student()
stu.accept()
stu.cal()
stu.dis()
Output:
Enter the register number 231827
Enter the name Spoorthi
Enter the english 89
Enter the maths 90
Enter the science 90
Register number: 231827
Name: Spoorthi
Marks 1: 89
Marks 2: 90
Marks 3: 90
Total: 269
Average: 89.66666666666667

Register Number:231827
Date: 12-11-2024
Program 5:Program to create Employee class(Eno, Ename, Dept, Basic, DA, HRA, IT,
Gross, Net) and demonstrate default constructor, parameterised constructor
—----------------------------------------------------------------------------------------------------------------
class Employee:
def __init__(self, Eno=0, Ename="Unknown", Dept="Unknown", Basic=0, DA=0, HRA=0,
IT=0):
"""Default and Parameterized Constructor"""
self.Eno = Eno
self.Ename = Ename
self.Dept = Dept
self.Basic = Basic
self.DA = DA
self.HRA = HRA
self.IT = IT
self.Gross = 0
self.Net = 0

def calculate_salary(self):
"""Calculate Gross and Net salary"""
self.Gross = self.Basic + self.DA + self.HRA
self.Net = self.Gross - self.IT

def display_employee_details(self):
"""Display Employee Details"""
print(f"Employee Number: {self.Eno}")
print(f"Employee Name: {self.Ename}")
print(f"Department: {self.Dept}")
print(f"Basic Salary: {self.Basic}")
print(f"DA (Dearness Allowance): {self.DA}")
print(f"HRA (House Rent Allowance): {self.HRA}")
print(f"Income Tax (IT): {self.IT}")
print(f"Gross Salary: {self.Gross}")
print(f"Net Salary: {self.Net}")

# Demonstrating Default Constructor


print("Using Default Constructor:")
employee1 = Employee()
employee1.calculate_salary()
employee1.display_employee_details()
# Demonstrating Parameterized Constructor
print("\nUsing Parameterized Constructor:")
employee2 = Employee(555, "Tamanvi", "HR", 50000, 10000, 8000, 5000)
employee2.calculate_salary()
employee2.display_employee_details()

Output:
Using Default Constructor:
Employee Number: 0
Employee Name: Unknown
Department: Unknown
Basic Salary: 0
DA (Dearness Allowance): 0
HRA (House Rent Allowance): 0
Income Tax (IT): 0
Gross Salary: 0
Net Salary: 0

Using Parameterized Constructor:


Employee Number: 555
Employee Name: Tamanvi
Department: HR
Basic Salary: 50000
DA (Dearness Allowance): 10000
HRA (House Rent Allowance): 8000
Income Tax (IT): 5000
Gross Salary: 68000
Net Salary: 63000

Register Number:231827
Date: 12-11-2024
Program 6: Program to create Person class (SSN, Name and Age) and create a list of 5
objects.
—------------------------------------------------------------------------------------------------------------------
class Person:
def __init__(self, SSN, Name, Age):
"""Parameterized Constructor"""
self.SSN = SSN
self.Name = Name
self.Age = Age

def display_details(self):
"""Display details of the person"""
print(f"SSN: {self.SSN}")
print(f"Name: {self.Name}")
print(f"Age: {self.Age}")

# List to store Person objects


person_list = []

# Create 5 Person objects and add them to the list


person_list.append(Person("254", "Chris", 30))
person_list.append(Person("452", "Dev", 25))
person_list.append(Person("995", "Sam", 35))
person_list.append(Person("266", "Anis", 28))
person_list.append(Person("459", "Eva", 40))

# Display details of all persons in the list


for person in person_list:
person.display_details()

Output:
SSN: 254
Name: Chris
Age: 30
SSN: 452
Name: Dev
Age: 25
SSN: 995
Name: Sam
Age: 35
SSN: 266
Name: Anis
Age: 28
SSN: 459
Name: Eva
Age: 40

Register Number:231827
Date: 12-11-2024
Program 7: Program to show multilevel inheritance (Student, Marks, Result class)
—------------------------------------------------------------------------------------------------------------------
class student():
rno=0
name=" "
age=0
def get(self):
self.rno=int(input("enter the register number:"))
self.name=input("enter the name")
self.age=int(input("Enter the age"))
def put(self):
print("Roll no: ",self.rno)
print("Name: ",self.name)
print("Age:",self.age)
class marks(student):
m1=0
m2=0
m3=0
def get(self):
super().get()
self.m1=int(input("enter the marks 1:"))
self.m2=int(input("enter the marks 2:"))
self.m3=int(input("enter the marks 3:"))
def put(self):
super().put()
print("Marks 1=",self.m1)
print("Marks 2=",self.m2)
print("Marks 3=",self.m3)
class result(marks):
tot=0
def get(self):
super().get()
self.tot=self.m1+self.m2+self.m3
def put(self):
super().put()
print("Total marks: ",self.tot)

r=result()
r.get()
r.put()
Output:
enter the register number: 4585
enter the name Neel
Enter the age 45
enter the marks 1: 78
enter the marks 2: 89
enter the marks 3: 78

Roll no: 4585


Name: Neel
Age:45
Marks 1= 78
Marks 2= 89
Marks 3= 78
Total marks: 245

Register Number:231827
Date: 12-11-2024
Program 8:Program to show multiple inheritance,
—------------------------------------------------------------------------------------------------------------------
class A:
def met1(self):
print("Class A")
class B:
def met2(self):
print("Class B")
class C(A,B):
def met3(self):
self.met1()
self.met2()
print("Class C")
c=C()
c.met3()

Output:
Class A
Class B
Class C
Register Number:231827
Date: 12-11-2024
Program 9:Program to show hierarchical inheritance
—------------------------------------------------------------------------------------------------------------------
from math import pi
class Shape:
def __init__(self,name):
self.name=name
def area(self):
pass
def fact(self):
return "I represent 2-dimensional shape."
def __str__(self):
return self.name
class square(Shape):
def __init__(self,length):
super().__init__("Square")
self.length=length
def area(self):
return self.length**2
def fact(self):
return "Square have each angle equal to 90"
class circle(Shape):
def __init__(self,radius):
super().__init__("Circle")
self.radius=radius
def area(self):
return pi*self.radius**2
a=square(10)
b=circle(7)
print(b)
print(b.fact())
print(a.fact())
print(b.area())
print(a.area())
Output:
Circle
I represent 2-dimensional shape.
Square have each angle equal to 90
153.93804002589985
100
Register Number:231827
Date: 12-11-2024
Program 10: Program to show Polymorphism using two classes, Student and Teacher. Both
classes should have the same method names, info() and msg(), but they should behave
differently when called on objects of each class
—------------------------------------------------------------------------------------------------------------------
class student:
def __init__(self,name):
self.name=name
def info(self):
print(f"I am {self.name}")
def msg(self):
print("I am Student")
class teacher:
def __init__(self,name):
self.name=name
def info(self):
print(f"I am {self.name}")
def msg(self):
print("I am Teacher")
S=student("Spoorthi")
T=teacher("Devi")
for val in (S,T):
val.msg()
val.info()

Output:
I am Student
I am Spoorthi
I am Teacher
I am Devi
Register Number:231827
Date: 12-11-2024
Program 11:Program to demonstrate ValueError, AssertionError for ATM money
withdrawal
—------------------------------------------------------------------------------------------------------------------

balance=10000 #initial balance

try:
withdrawal=int(input("Enter the amount to be withdraw:"))
assert withdrawal>0,"Error:withdrawal amount must be positive"

if withdrawal>balance:
raise ValueError("Error :Insufficient balance")
balance -= withdrawal
print(f"withdrawal Successfull!New balance:{balance}")
except ValueError as ve:
print(ve)
except Assertionerror as ae:
print(ae)
finally:
print("Thank you for using the ATM")

Output:
Enter the amount to be withdraw:8000
withdrawal Successfull!New balance:2000
Thank you for using the ATM
Register Number:231827
Date: 12-11-2024
Program12:Program to create a hierarchy of user defined Exception classes namely
NegativeNumberError, DivisionByZeroError and CalculationError that inherits from the
previous two parent classes and test the exceptions
—------------------------------------------------------------------------------------------------------------------
# Parent Exception Class 1
class NegativeNumberError(Exception):
def __init__(self, message="Negative number encountered"):
self.message = message
super().__init__(self.message)

# Parent Exception Class 2


class DivisionByZeroError(Exception):
def __init__(self, message="Division by zero error"):
self.message = message
super().__init__(self.message)

# Child Exception Class inherited from both NegativeNumberError and DivisionByZeroError


class CalculateError(NegativeNumberError, DivisionByZeroError):
def __init__(self, message):
super().__init__(message)

# Function that raises errors based on input


def perform_Calculation(num1, num2):
if num1 < 0 or num2 < 0:
raise CalculateError("Error: Negative numbers are not allowed")
elif num2 == 0:
raise CalculateError("Error: Division by zero is not allowed")
else:
return num1 / num2
# Testing the code
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

result = perform_Calculation(num1, num2)


print(f"Result: {result}")
except CalculateError as e:
print(e)
Output:
Enter first number: 5
Enter second number: 0
Error: Division by zero is not allowed
Register Number:231827
Date: 12-11-2024
Program 13:Python program to create simple shopping cart system. Also create a custom
exception to handle exception where a user tries to purchase more items than that are
available in stock.
—------------------------------------------------------------------------------------------------------------------

class OutOfStockError(Exception):
"""Exception raised for trying to purchase more items than availble in stock"""
def __init__(self,item,requested_item,available_amount):
self.item=item
self.requested_item=requested_item
self.available_amount=available_amount
self.message=(
f"insufficient stock for'{item}'."
f"Requested:{requested_amount},Available:{available_qty}."
)
super().__init__(self.message)
class shoppingCart:
def __init__(self):
self.stock={}
def add_item(self,item,quantity):
self.stock[item]=self.stock.get(item,0)+quantity
print(f"Added {quantity} of '{item}' to stock.Current stock:{self.stock[item]}")
def purchase(self,item,quantity):
if item not in self.stock:
raise OutOfStockError(item,quantity,0)
if quantity>self.stock[item]:
raise OutOfStockError(item,quantity,self.stock[item])
self.stock[item]-=quantity
print(f"Purchased {quantity} of '{item}'.Remaining stock:{self.stock[item]}")
try:
cart=shoppingCart()
ch='y'
while(ch=='y'):
name=input("Enter item to add")
qty=int(input("Enter the qty"))

cart.add_item(name,qty)
ch=input("do you want to continue(y/o)")
item_to_purchase=input("Enter the item you want to purchase:")
quantity_to_purchase=int(input(f"Enter the quantity of '{item_to_purchase}'"))
cart.purchase(item_to_purchase,quantity_to_purchase)
except OutOfStockError as e:
print(e)
except ValueError:
print("Invalid input:Please enter a valid number")
Output:
Enter item to addFan
Enter the qty5
Added 5 of 'Fan' to stock.Current stock:5
do you want to continue(y/o)y
Enter item to addLight
Enter the qty4
Added 7 of 'Light' to stock.Current stock:4
do you want to continue(y/o)o
Enter the item you want to purchase:Light
Enter the quantity of 'Light'2
Purchased 2 of 'Light’.Remaining stock:2

You might also like