0% found this document useful (0 votes)
8 views45 pages

Python Manual For M.SC CS

Uploaded by

lakshmi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
8 views45 pages

Python Manual For M.SC CS

Uploaded by

lakshmi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 45

Ex.

No: 1 ARITHMETIC OPERATIONS

Aim:
To write a python program to calculate the arithmetic operations.

Code:

con = 'y'

while con=='y':

print('\nArithmetic Operations')

print('---------------------\n')

print('1.Addition')

print('2.Subrtraction')

print('3.Multiplication')

print('4.division\n')

print('Enter the Choice')

co=int(input())

match co:

case 1:

a=int(input('\nEnter the first value '))

b=int(input('Enter the second value '))

print('The addition value is',a+b)

case 2:

a=int(input('\nEnter the first value '))

b=int(input('Enter the second value '))

print('The subtraction value is',a-b)

case 3:

a=int(input('\nEnter the first value '))


b=int(input('Enter the second value '))

print('The multiplication value is',a*b)

case 4:

a=int(input('\nEnter the first value '))

b=int(input('Enter the second value '))

print('The division value is',a/b)

con=input('\nDo you want to continue? (y / n) ')

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 2 PRIME / PERFECT NUMBER CHECKING

Aim:

To write a python to calculate prime and perfect no.

Code:

con = 'y'

while con=='y':

print('\n Prime / Perfect Number Checking')

print('----------------------------------\n')

print("1.Prime no Checking")

print("2.Perfect no Checking")

print("\nEnter The Choice: ")

co=int(input())

match co:

case 1:

a=int(input("Enter The Number: "))

flag=0

for i in range(2,(a//2)+1):

if(a%i==0):

flag=1

break

if(flag==1):

print(a,"is not Prime")

else:

print(a,"is Prime")
case 2:

a=int(input("Enter The Number: "))

b=0

for i in range(1,a):

if(a%i==0):

b=b+i

if(b==a):

print(a,"is perfect")

else:

print(a,"is not perfect")

con=input('\nDo you want to continue y / n ')

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 3 ADAM / ARMSTRONG NUMBER CHECKING

Aim:

To Write a python program to find the Adam Number and Armstrong Number.

Code :

con = 'y'

while con=='y':

print('\n ADAM / ARMSTRONG NUMBER CHECKING')

print('-----------------------------------\n')

print("1.Adam no Checking")

print("2.Armstrong no Checking")

print("\nEnter The Choice")

co=int(input())

match co:

case 1:

def reverseDigits(num) :

rev = 0

while (num > 0) :

rev = rev * 10 + num % 10

num //= 10

return rev

def square(num) :

return (num * num)

def checkAdamNumber(num) :

a = square(num)
b = square(reverseDigits(num))

return a==reverseDigits(b)

num = int(input("\nEnter The Number: "))

if checkAdamNumber(num):

print (num,"isa Adam Number")

else:

print (num,"is not a Adam Number")

case 2:

num = int(input("\nEnter a number: "))

sum = 0

temp = num

while temp > 0:

digit = temp % 10

sum += digit ** 3

temp //= 10

if num == sum:

print(num,"is an Armstrong number")

else:

print(num,"is not an Armstrong number")

con=input('Do you want to continue y / n ')

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 4 TO CREATE AN ALARM

Aim:
To Write a python program to create an Alarm.

Code:
import datetime

import winsound

print('\nCREATE an ALARM')

print('-----------------\n')

def set_alarm(alarm_time):

print(f"Alarm set for {alarm_time}")

while True:

current_time = datetime.datetime.now()

if current_time.hour == alarm_time.hour and current_time.minute


==alarm_time.minute:

print("Wake Up!")

winsound.Beep(2500, 1000) # play a beep sound

break

def main():

alarm_hour = int(input("Enter the hour for the alarm: "))

alarm_minute = int(input("Enter the minute for the alarm: "))

alarm_time = datetime.datetime.now()

alarm_time = alarm_time.replace(hour=alarm_hour, minute=alarm_minute,

second=0)

set_alarm(alarm_time)
if __name__ == "__main__":

main()

Result:

Thus the program was successfully executed and the output was verified.
Output:
Ex.No: 5 PAINT PROGRAM (ROSETTE) USING TURTLE

Aim:

To Write a Python Program to create paint program (rosette) using turtle.

Code:

import turtle

from turtle import *

print('\nPAINT PROGRAM(ROSETTE) USING TURTLE')

print('-------------------------------------\n')

def part( total, length, breadth, col ):

angleInc = 360/total

width( breadth )

color( col )

for i in range(total):

forward( length )

left( angleInc )

def rosette( total, length, width, color, angleInc ):

for i in range( int(360/angleInc) ):

part( total, length, width, color )

left( angleInc )

turtle.setup( 500, 500, 100, 100 )


turtle.speed(0)

title("Rosette - original from website no longer active")

rosette(10,40,1,"blue",36)

rosette(5,80,1,"red",36)

turtle.exitonclick()

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 6 LIST OPERATIONS

Aim:
To Write a python program and check the following operations in List.
i) Insert
ii) Delete
iii) Sort
iv) Reversed
v) Slice a list
vi) Sum and Average

Code:

print('\nLIST OPERATIONS')

print('-----------------\n')

my_list=[]

print("""1.Insert 2.Remove 3.Sort the list 4.Reverse the list \n5.Slice a List
6.Sum 7. Average""")

con='y'

while con=='y':

choice=int(input("\nEnter your choice : "))

match choice:

case 1:

item=int(input("\nEnter item to insert:"))

my_list.append(item)

print("List after Insertion : ",my_list)

case 2:

item=int(input("\nEnter item to remove:"))

my_list.remove(item)
print("Removed list : ",my_list)

case 3:

my_list.sort()

print("Sorted list : ",my_list)

case 4:

my_list.reverse()

print("Reversed list : ",my_list)

case 5:

start = int(input("\nEnter start index for slice : "))

end = int(input("\nEnter end index for slice : "))

sliced_list = my_list[start:end]

print("Sliced list : ",sliced_list)

case 6:

total_sum=sum(my_list)

print("Sum of the list : ",total_sum)

case 7:

avg=sum(my_list)/len(my_list)

print("Average of the list : ",avg)

con=input("\nDo you want to continue? (y/n) ")

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 7 TUPLE OPERATIONS

Aim:
To Write a python program and check the following operations in Tuples.
i) Concatenation
ii) Slice a Tuple
iii) Count
iv) Search
v) Maximum and Minimum

Code:
print('\nTUPLE OPERATIONS')

print('------------------\n')

my_tuple1=(1,2,3,5,2,6,3,5)

my_tuple2=("Hello","World")

print(my_tuple1)

print(my_tuple2)

print("""1) Concatenation 2) Slice a Tuple 3) Count \n4) Search 5) Maximum and


Minimum """)

con='y'

while con=='y':

choice=int(input("\nEnter your choice : "))

match choice:

case 1:

concatenated_tuple=my_tuple1+my_tuple2

print("Concatenation of 2 Tuples :",concatenated_tuple)

case 2:

start = int(input("Enter start index for slice: "))

end = int(input("\nEnter end index for slice: "))

sliced_tuple=my_tuple1[start:end]
print(sliced_tuple)

case 3:

numm=int(input("Enter a number to count : "))

count_of_5=my_tuple1.count(numm)

print("\nCount of",numm,"is",count_of_5)

case 4:

search_item=int(input("Enter the item to search: "))

if search_item in my_tuple1:

print(search_item,"is found")

else:

print(search_item,"is not found")

case 5:

max_val=max(my_tuple1)

min_val=min(my_tuple1)

print("Maximum value is:",max_val)

print("Minimum value is:",min_val)

con=input("Do you want to continue? (y/n) ")

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 8 DICTIONARIES

Aim:
To Write a python program and check the following operations in Dictionaries.
i) Insert
ii) Delete / Remove
iii) Search
iv) Display Keys
v) Display Values
Code:
print('\nDICTIONARY OPERATIONS')

print('-----------------------\n')

dict={}

print("""1)Insert 2) Delete / Remove 3) Search \n4) Display Keys 5) Display


Values""")

con='y'

while con=='y':

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

match choice:

case 1:

key = input("Enter the key: ").strip()

value= input("Enter the value: ").strip()

dict[key] = value

print(dict)

case 2:

key = input("Enter the key to remove: ").strip()

if key in dict:

del dict[key]

print("Key removed",dict)

else:

print("Key not found.")


case 3:

key = input("Enter the key to search for: ").strip()

value = dict.get(key)

if value:

print(f"{key}: {value}")

else:

print("Key not found.")

case 4:

print("Keys:", list(dict.keys()))

case 5:

print("value", list(dict.values()))

con=input("Do you want to continue? (y/n) ")

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 9 SET

Aim:
To Write a python program and check the following operations in Set.
i) Union
ii) Intersection
iii) Difference
iv) Equal or Not Equal
Code:
A={1,2,6,8,9}

B={0,5,7,2,6}

print(A)

print(B)

print("""1)Union

2) Intersection

3) Difference

4) Equal or Not Equal""")

con='y'

while con=='y':

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

match choice:

case 1:

print("union of two sets:",A.union(B))

case 2:

print("intersection of two sets:",A.intersection(B))

case 3:

print("difference of two sets:",A.difference(B))

case 4:

if(A==B):

print("Set A and Set B are equal")


else:

print("Set A and Set B are not equal")

con=input("Do you want to continue? (y/n) ")

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 10 EXCEPTION HANDLING

Aim:
To write a python program for Exception handling.
Code:
print('\nEXCEPTION HANDLING')

print('--------------------\n')

def get_numeric_input(prompt):

while True:

try:

value = float(input(prompt))

return value

except ValueError:

print("Error: Invalid input. Please Input a valid number.")

n1 = get_numeric_input("Input the first number: ")

n2 = get_numeric_input("Input the second number: ")

result = n1 * n2

print("Product of the said two numbers:", result)

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 11 DISPLAY STUDENT DETAILS

Aim:
To write a python program to display student details.
Code:
print('\nDISPLAY STUDENT DETAILS')
print('-------------------------\n')

class Student:
def getStudentDetails(self):
self.rollno = input("Enter Roll Number : ")
self.name = input("Enter Name : ")
self.cpp = int(input("Enter cpp Marks : "))
self.java = int(input("Enter Java Marks : "))
self.css = int(input("Enter Python Marks : "))

def total(self):
self.total_marks = self.cpp + self.java + self.css

def avg(self):
self.average_marks = (self.cpp + self.java + self.css) / 300 * 100

def grade(self):
if self.average_marks>= 90:
return "A"
elifself.average_marks>= 80:
return "B"
elifself.average_marks>= 70:
return "C"
elifself.average_marks>= 60:
return "D"
else:
return "F"
def display_details(self):
print("Student Details:")
print("Roll Number:", self.rollno)
print("Name:", self.name)
print("Total Marks:", self.total_marks)
print("Average Marks:", self.average_marks)
print("Grade:", self.grade())
S1 = Student()
S1.getStudentDetails()
S1.total()
S1.avg()
S1.display_details()
Result:
Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 12 EMPLOYEE DATA’S STORED

Aim:
To write a python program to employee data’s stored.

Code:

print('\nDISPLAY EMPLOYEE DETAILS')

print('--------------------------\n')

class Employee:

def __init__(self):

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

self.id = input("Enter Id: ")

self.salary = int(input("Enter the Salary: "))

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

def calculate_salary(self, hours_worked):

overtime = 0

if hours_worked > 50:

overtime = hours_worked - 50

self.salary += overtime * (self.salary / 50)

def print_employee_details(self):

print("\nName: ", self.name)

print("ID: ", self.id)

print("Salary: ", self.salary)

print("Department: ", self.department)


print("----------------------")

# Driver Code

n = int(input("Enter the number of employees: "))

employees = []

for i in range(n):

print(f"\nEnter details for employee {i + 1}:")

emp = Employee()

hours_worked = int(input(f"Enter hours worked for employee {i + 1}: "))

emp.calculate_salary(hours_worked)

employees.append(emp)

# Output details of all employees

print("\nEmployee Details:")

for emp in employees:

emp.print_employee_details()

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 13 RESTAURANT MANAGEMENT

Aim:
To write a python program for Restaurant Management.

Code:

class Restaurant:

def __init__(self):

# Predefined menu items

self.menu_items = {

"Cheeseburger": 9.99,

"Caesar Salad": 8.00,

"Grilled Salmon": 19.99,

"French Fries": 3.99,

"Fish & Chips": 15.00

self.book_table = []

self.customer_orders = []

def book_table(self, table_number):

if table_number not in self.book_table:

self.book_table.append(table_number)

else:

print(f"Table {table_number} is already reserved!")

def customer_order(self, table_number, order):


if order in self.menu_items:

order_details = {'table_number': table_number, 'order': order}

self.customer_orders.append(order_details)

else:

print(f"Sorry, {order} is not available on the menu.")

def print_menu_items(self):

print("\nMenu:")

for item, price in self.menu_items.items():

print(f"{item}: ${price:.2f}")

def print_table_reservations(self):

print("\nTables reserved:")

for table in self.book_table:

print(f"Table {table}")

def print_customer_orders(self):

print("\nCustomer orders:")

for order in self.customer_orders:

print(f"Table {order['table_number']}: {order['order']}")

# Driver code

restaurant = Restaurant()

# Display the menu to the user

restaurant.print_menu_items()

# Customer bookings and orders


c = int(input("\nEnter the number of customers: "))

for _ in range(c):

table_number = int(input("Enter the table number for booking: "))

# Book the table

restaurant.book_table(table_number)

order = input("Enter the customer's order: ")

restaurant.customer_order(table_number, order)

# Display results

restaurant.print_menu_items()

restaurant.print_table_reservations()

restaurant.print_customer_orders()

Result:

Thus the program was successfully executed and the output was verified.

Output:

Menu:

Cheeseburger: $9.99

Caesar Salad: $8.00


Grilled Salmon: $19.99

French Fries: $3.99

Fish & Chips: $15.00

Enter the number of customers: 2

Enter the table number for booking: 1

Enter the customer's order: Cheeseburger

Enter the table number for booking: 2

Enter the customer's order: Grilled Salmon

Menu:

Cheeseburger: $9.99

Caesar Salad: $8.00

Grilled Salmon: $19.99

French Fries: $3.99

Fish & Chips: $15.00

Tables reserved:

Table 1

Table 2

Customer orders:

Table 1: Cheeseburger

Table 2: Grilled Salmon

Ex.No: 14 SINGLE INHERITANCE

Aim:

To write a python program using single Inheritance

Code:
class Person:

def __init__(self, name, age):

self.name = name

self.age = age

def display_details(self):

print("Name: " + self.name)

print("Age: " + str(self.age))

class Employee(Person):

def __init__(self, name, age, empid, dept):

super().__init__(name, age)

self.emp_id = empid

self.dept = dept

def display_empdetails(self):

self.display_details()

print("Employee ID: " + self.emp_id)

print("Department: " + self.dept)

# Driver Code

name = input("Enter the employee's name: ")

age = int(input("Enter the employee's age: "))

empid = input("Enter the employee ID: ")

dept = input("Enter the employee's department: ")


emp = Employee(name, age, empid, dept)

print("\nEmployee Details:")

emp.display_empdetails()

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 15 MULTIPLE INHERITANCE

Aim:

To write a python program using multiple inheritance

Code:

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

def display_personal_details(self):

print("Name: " + self.name)

print("Age: " + str(self.age))

class Department:

def __init__(self, empid, dept):

self.emp_id = empid

self.dept = dept

def display_dept_details(self):

print("Employee ID: " + self.emp_id)

print("Department: " + self.dept)

class Employee(Person, Department):


def __init__(self, name, age, empid, dept):

Person.__init__(self, name, age)

Department.__init__(self, empid, dept)

def display_emp_details(self):

self.display_personal_details()

self.display_dept_details()

# Driver Code

name = input("Enter the employee's name: ")

age = int(input("Enter the employee's age: "))

empid = input("Enter the employee ID: ")

dept = input("Enter the employee's department: ")

emp = Employee(name, age, empid, dept)

print("\nEmployee Details:")

emp.display_emp_details()

Result:

Thus the program was successfully executed and the output was verified.

Output:
Ex.No: 16 File Operations

Aim:

To write a python program to perform File Operations.

Code:

file = open("example.txt", "w")

file.write("This is the first line.\n")

file.write("This is the second line.\n")

file.close()

file = open("example.txt", "r")

content = file.read()

print("File content:\n", content)

file.close()

file = open("example.txt", "a")

file.write("This is the third line.\n")

file.close()

file = open("example.txt", "r")

content = file.read()

print("Updated file content:\n", content)

file.close()

Result:
Thus the program was successfully executed and the output was verified.

Output:

You might also like