0% found this document useful (0 votes)
2 views104 pages

Python Lab

The document contains various Python programming exercises focusing on conditional statements, loops, string functions, and list functions. Each section includes an aim, program code, output, and result indicating successful execution. The exercises demonstrate practical applications of Python concepts such as checking number properties, generating patterns, and manipulating strings and lists.

Uploaded by

mukesh148y
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)
2 views104 pages

Python Lab

The document contains various Python programming exercises focusing on conditional statements, loops, string functions, and list functions. Each section includes an aim, program code, output, and result indicating successful execution. The exercises demonstrate practical applications of Python concepts such as checking number properties, generating patterns, and manipulating strings and lists.

Uploaded by

mukesh148y
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

Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -

600004
Ex
No.
CONDITIONAL STATEMENTS-IF
1 (a)

AIM:
To write a python program to check if a number is positive and less than 10 using if
statement.

PROGRAM:
# Checking if a number is positive and less than 10
num = int(input("Enter a number: "))
if num > 0 and num < 10:
print("The number is positive and less than 10.")

OUTPUT:
Enter a number: 8
The number is positive and less than 10.

RESULT:
Thus the python program to check if a number is positive and less than 10 using if statement
has been executed successfully.

1
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
CONDITIONAL STATEMENTS-IF..ELSE
1 (b)

AIM:
To write a python program to check whether a number is divisible by 5 using if..else
statement.

PROGRAM:
# Checking divisibility

num = int(input("Enter a number:


")) if num % 5 == 0:
print(f"{num} is divisible by 5.")
else:
print(f"{num} is not divisible by 5.")

OUTPUT:
Enter a number: 225
225 is divisible by 5.

RESULT:
Thus the python program to check if a number is divisible by 5 using if..else statement has
been executed successfully.

2
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex No.

1 (c) CONDITIONAL STATEMENTS-IF..ELIF..ELSE

AIM:
To write a python program to find the grade for a given mark using if..elif..else statement.

PROGRAM:
# Grading system

marks = int(input("Enter your mark: "))


if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")

OUTPUT:

Enter your mark: 78


Grade: B

RESULT:

Thus the python program to find the grade for a given mark using if..elif..else statement has
been executed successfully.

3
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
CONDITIONAL STATEMENTS - NESTED IF ELSE
1 (d)

AIM:
To write a python program to find the greatest of three numbers using nested if..else
statements.

PROGRAM:
# Input: Getting three numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Using nested if...else to find the greatest


number if num1 >= num2:
if num1 >= num3:
print(f"The greatest number is {num1}")
else:
print(f"The greatest number is {num3}")
else:
if num2 >= num3:
print(f"The greatest number is {num2}")
else:
print(f"The greatest number is {num3}")

4
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

OUTPUT:

Enter the first number: 5


Enter the second number:
10 Enter the third number: 2
The greatest number is 10.0

RESULT:
Thus the python program to find the greatest of three numbers has been executed
successfully.

5
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
CONTROL STATEMENT - FOR LOOP
2 (a)

AIM:
To write a python program to find the square of numbers from 1 to 5 using a for loop.
PROGRAM:
# Printing squares of numbers from 1 to
5 for i in range(1, 6):
print(f"Square of {i}: {i*i}")

OUTPUT:
Square of 1: 1
Square of 2: 4

Square of 3: 9
Square of 4: 16
Square of 5: 25

RESULT:
Thus the python program to find the square of numbers from 1 to 5 has been executed
successfully.

6
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
CONTROL STATEMENT - NESTED FOR LOOP
2 (b)

AIM:
To write a python program that displays a 5x5 pattern of stars using a nested for loop.

PROGRAM :
# Printing a 5x5 pattern of
stars for i in range(5):
for j in range(5):
print("*", end=" ")
print()

OUTPUT:
*****
*****
*****
*****

*****

RESULT:
Thus the python program that displays a 5x5 pattern of stars has been executed successfully.

7
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex CONTROL STATEMENTS
No.
USING BREAK
2 (c)

AIM:

To write a python program that uses the break keyword to come out of the loop when a
certain condition is met.

PROGRAM:
for i in range(1, 11):
if i == 7:
print("Stopped at", i)
break
print(i)

OUTPUT:

1
2

3
4
5

6
Stopped at 7

RESULT:
Thus the python program that uses the break keyword to come out of the loop when a
certain condition is met has been executed successfully.

8
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex CONTROL STATEMENTS
No.
USING CONTINUE
2 (d)

AIM:

To write a python program to skip the multiples of 3 using continue keyword.


PROGRAM:
# Skipping multiples of 3
for i in range(1, 11):
if i % 3 == 0:

continue

print(i)
OUTPUT:
1
2
4
5
7
8
10

RESULT:

Thus the python program to skip the multiples of 3 has been executed successfully.

9
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex CONTROL STATEMENTS
No.
WHILE LOOP
2 (e)

AIM:

To write a python program to check whether the given number is palindrome or not using
while loop.

PROGRAM:
n=int(input("Enter Number: "))
m=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if rev==m:

print(m,"is Palindrome")
else:
print(m,"is not Palindrome")

OUTPUT:

Enter Number: 1221


1221 is Palindrome

RESULT:
Thus the python program to check whether the given number is palindrome or not using a
while loop has been executed successfully.

10
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
STRING AND RELATED FUNCTIONS
3 A)

AIM:
To write a python program to demonstrate string functions.

PROGRAM:
# Define a sample string
sample_text = " Hello, Welcome to the world of Python. "

# 1. upper(): Convert all characters to uppercase


print("In Upper Case ",sample_text.upper())

# 2. lower(): Convert all characters to lowercase


print("In Lower Case",sample_text.lower())

# 3. strip(): Remove leading and trailing whitespaces


print("After Removing Leading and Trailing whitespaces:\n",sample_text.strip())

# 4. replace(): Replace occurrences of a substring with another substring


print("After Replace: ",sample_text.replace("Python", "Programming"))

# 5. split(): Split the string into a list based on a delimiter


print("Splitting: ",sample_text.split())

# 6. join(): Join elements of a list into a single string with a specified


separator words = ['Hello', 'world', 'join', 'example']

11
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
print("Joining a list of words: "," ".join(words))

# 7. find(): Find the index of the first occurrence of a substring, -1 if not


found print("Find the position of substring 'Python':
",sample_text.find("Python"))

# 8. startswith(): Check if the string starts with a specific substring


print("does the sentence start with hello? ",sample_text.startswith("Hello"))

# 9. endswith(): Check if the string ends with a specific substring


print("does the sentence start with
'.'",sample_text.endswith("."))

# 10. count(): Count occurrences of a substring in the string


print("How many 'o' are there in the sample text? ",sample_text.count("o"))

text_alpha = "Python"
text_digit = "12345"
text_alnum = "Python123"

text_space = " " # Contains only spaces


text_title = "Python Programming"

# 11. isalpha(): Check if the string contains only alphabetic characters


print(f"'{text_alpha}' is alphabetic:", text_alpha.isalpha())

# 12. isdigit(): Check if the string contains only numeric characters


print(f"'{text_digit}' is numeric:", text_digit.isdigit())

# 13. isalnum(): Check if the string contains only alphanumeric characters (letters and numbers)
12
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
print(f"'{text_alnum}' is alphanumeric:", text_alnum.isalnum())

13
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

# 14. isspace(): Check if the string contains only whitespace characters


print(f"'{text_space}' contains only spaces:", text_space.isspace())

# 15. istitle(): Check if the string follows title case (first letter of each word is uppercase)
print(f"'{text_title}' is in title case:", text_title.istitle())

OUTPUT:
In Upper Case HELLO, WELCOME TO THE WORLD OF PYTHON.
In Lower Case hello, welcome to the world of python.
After Removing Leading and Trailing whitespaces:
Hello, Welcome to the world of Python.
After Replace: Hello, Welcome to the world of Programming.
Splitting: ['Hello,', 'Welcome', 'to', 'the', 'world', 'of',
'Python.'] Joining a list of words: Hello world join example
Find the position of substring 'Python':
33 does the sentence start with hello?
False does the sentence start with '.'
False
How many 'o' are there in the sample text? 6
'Python' is alphabetic: True
'12345' is numeric: True
'Python123' is alphanumeric: True
' ' contains only spaces: True
'Python Programming' is in title case: True

RESULT:

Thus the python program to demonstrate string functions has been executed successfully.

14
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
COUNT VOWELS IN A STRING
3 B)

AIM:
To write a python program that counts the no. of vowels, consonants and whitespaces in a
given string.

PROGRAM:
def count_characters(string):
vowels = "aeiouAEIOU"
vowel_count = 0
consonant_count = 0

whitespace_count = 0

for char in string:


if char in vowels:
vowel_count += 1
elif [Link](): # Checks if the character is a letter
consonant_count += 1
elif [Link](): # Checks if the character is a space
whitespace_count += 1

return vowel_count, consonant_count, whitespace_count

# Input from the user


text = input("Enter a string: ")

15
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

# Count characters
vowels, consonants, whitespaces = count_characters(text)

# Display the results


print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Whitespaces: {whitespaces}")

OUTPUT:

Enter a string: Welcome to the world of python


Vowels: 8
Consonants: 17
Whitespaces: 5

RESULT:

Thus the python program that counts the no. of vowels, consonants and whitespaces in a
given string has been executed successfully.

16
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
LIST RELATED FUNCTIONS
3 c)

AIM:
To write a python program that demonstrates various list functions.

PROGRAM:
# Define a sample list
sample_list = [1, 2, 3, 4, 5, 2, 3, 6]

# 1. append(): Add an element to the end of the list


print("After append:", sample_list)

# 2. extend(): Add elements of another list to the existing list


sample_list.extend([7, 8, 9])
print("After extend:", sample_list)

# 3. insert(): Insert an element at a specific index


sample_list.insert(0, 0) # Insert 0 at index 0
print("After insert:", sample_list)

# 4. remove(): Remove the first occurrence of an element


sample_list.remove(4) # Remove the number 4
print("After remove:", sample_list)

# 5. pop(): Remove and return an element at a specific index (default is the last)

17
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
removed_element = sample_list.pop() # Remove the last element
print("After pop:", sample_list, "| Removed element:", removed_element)

# 6. index(): Get the index of the first occurrence of an element


index_of_two = sample_list.index(2)
print("Index of 2:", index_of_two)

# 7. count(): Count the number of occurrences of an element in the list


count_of_two = sample_list.count(2)
print("Count of 2:", count_of_two)

# 8. sort(): Sort the list in ascending order


sample_list.sort()
print("After sort:", sample_list)

# 9. reverse(): Reverse the order of elements in the list


sample_list.reverse()
print("After reverse:", sample_list)

# 10. copy(): Create a shallow copy of the


list copied_list = sample_list.copy()
print("Copied list:", copied_list)

# 11. clear(): Remove all elements from the list


sample_list.clear()
print("After clear:", sample_list)

18
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
OUTPUT:
After append: [1, 2, 3, 4, 5, 2, 3, 6]
After extend: [1, 2, 3, 4, 5, 2, 3, 6, 7, 8, 9]
After insert: [0, 1, 2, 3, 4, 5, 2, 3, 6, 7, 8, 9]
After remove: [0, 1, 2, 3, 5, 2, 3, 6, 7, 8, 9]

After pop: [0, 1, 2, 3, 5, 2, 3, 6, 7, 8] | Removed element: 9


Index of 2: 2
Count of 2: 2
After sort: [0, 1, 2, 2, 3, 3, 5, 6, 7, 8]
After reverse: [8, 7, 6, 5, 3, 3, 2, 2, 1, 0]

Copied list: [8, 7, 6, 5, 3, 3, 2, 2, 1, 0]


After clear: []

RESULT:

Thus the python program that demonstrates various list functions has been successfully
executed.

19
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
SPLIT NUMBERS IN A LIST
3 d)

AIM:
To write a python program that splits odd and even numbers from a given list.

PROGRAM:

# declare and assign list1


list1 = [11, 22, 33, 44, 55]

# declare listOdd - to store odd numbers


# declare listEven - to store even
numbers listOdd = []
listEven = []

# check and append odd numbers in


listOdd # and even numbers in listEven
for num in list1:
if num%2 == 0:

[Link](num)
else:

[Link](num)

# print lists

print( "list1: ", list1 )


20
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
print( "listEven: ", listEven)
print( "listOdd: ", listOdd)

OUTPUT:

list1: [11, 22, 33, 44, 55]


listEven: [22, 44]
listOdd: [11, 33, 55]

RESULT:
Thus the python program for splitting odd and even numbers in the given list is executed
successfully.

21
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
TUPLES
3 e)

AIM:
To write a python program that demonstrates the use of tuple and its related functions.

PROGRAM:
# empty tuple
my_tuple = ()
print("Empty tuple :", my_tuple, type(my_tuple))

#tuple having one element will become an integer by default


my_tuple = (100)
print("Result: ",my_tuple, " | Type: ", type(my_tuple) )

#tuple having one element with a comma after it won't be converted into integer
my_tuple = (100,)
print("With Comma, Result: ",my_tuple, " | Type: ", type(my_tuple) )

# tuple having integers


my_tuple = (1, 2, 3)
print("Tuple with integers :", my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4, 2, 2)
print("Tuple with mixed data types :", my_tuple)

22
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

print("Accessing tuple using index: ", my_tuple[1])

# Returns the index of the first occurrence of a specified value.


print("First Occurrence of 2 is at : ", my_tuple.index(2))

# Returns the no. of times a specified element has occurred


print("Count no. of times 2 has occurred: ",my_tuple.count(2))

# nested tuple

my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))


print("Nested tuples :", my_tuple)

# tuple can be created without parentheses also called tuple packing


my_tuple = 3, "dog", 4.6
print("Tuple is created without parentheses ", my_tuple)

# tuple unpacking is also possible


a, b, c = my_tuple
print("Tuple unpacking: ", a, b, c)

n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))


print("Accessing nested tuple :", n_tuple[2][2])

print("Before deleting in tuple ", my_tuple)


del my_tuple

# checking whether my_tuple exist in the scope where it was defined

23
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
if not 'my_tuple' in
locals(): print("Tuple is
deleted ")
else:
print("Tuple is not deleted")

tuple1 = [2]
print(tuple1,type(tuple1))

OUTPUT:
Empty tuple : () <class 'tuple'>
Result: 100 | Type: <class 'int'>
With Comma, Result: (100,) | Type: <class 'tuple'>
Tuple with integers : (1, 2, 3)
Tuple with mixed data types : (1, 'Hello', 3.4, 2, 2)
Accessing tuple using index: Hello
First Occurrence of 2 is at : 3
Count no. of times 2 has occurred: 2
Nested tuples : ('mouse', [8, 4, 6], (1, 2, 3))
Tuple is created without parentheses (3, 'dog',
4.6) Tuple unpacking: 3 dog 4.6
Accessing nested tuple : 3
Before deleting in tuple (3, 'dog', 4.6)
Tuple is deleted
[2] <class 'list'>

RESULT:
Thus the python program that demonstrates the use of tuple and its related functions has
been executed successfully.
24
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex FUNCTIONS - NO ARGUMENTS AND NO
No. RETURN VALUE

4 a)

AIM:

To write a python program that performs addition using a function with no arguments and
no return value.

PROGRAM:
# Python Function with No Arguments, and No Return Value
def Adding():
a = 20
b = 30
Sum = a + b
print("After Calling the Function:",
Sum) Adding()

OUTPUT:
After Calling the Function: 50

RESULT:
Thus the python program that performs addition using a function with no arguments and no return
value has been executed successfully.

25
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex No. FUNCTIONS - WITH ARGUMENTS AND
NO RETURN VALUE
4 b)

AIM:

To write a python program that greets a user using a function with arguments and no return
value.

PROGRAM:

# Function that takes a name and prints a greeting


def greet(name):
print(f"Hello, {name}! Welcome to Python .")

# Taking user input

user_name = input("Enter your name:


") greet(user_name)

OUTPUT:
Enter your name: john

Hello, john! Welcome to Python .

RESULT:
Thus, the python program that greets a user using a function with arguments and no return
value has been successfully executed.

26
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex FUNCTIONS - WITH ARGUMENTS AND
No. RETURN VALUE

4 c)

AIM:

To write a python program that finds the square of a given number using a function with
arguments and a return value.

PROGRAM:

# Function that returns the square of a


number def square(num):
return num * num

# Taking user input


num = int(input("Enter a number: "))
print("Square of the number:",
square(num))

OUTPUT:
Enter a number: 8
Square of the number:
64

RESULT:
Thus, the Python program that finds the square of a given number using a function with
27
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
arguments600004
and a return value has been successfully executed.

28
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex FUNCTIONS - DEFAULT ARGUMENTS
No.

4 d)

AIM:

To write a Python program that greets a user using a function with default arguments.

PROGRAM:

# Function with a default


argument def
greet(name="User"):
print(f"Hello, {name}!")

# Calling function with and without argument


greet() # Uses default value
greet("Alice") # Uses provided value

OUTPUT:
Hello, User!
Hello, Alice!

RESULT:

Thus, the Python program that greets a user using a function with default arguments has
been successfully executed.
29
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex No. FUNCTIONS - KEYWORD ARGUMENTS

4 e)

AIM:
To write a python program that displays student details using a function with keyword
arguments.

PROGRAM:
# Function that prints student details
def student_details(name, age, course):
print(f"Student Name: {name}")
print(f"Age: {age}")
print(f"Course: {course}")

# Calling function using keyword arguments


student_details(course="Computer Science", name="Alice", age=20)

OUTPUT:
Student Name: Alice
Age: 20
Course: Computer Science

RESULT:

Thus the python program that displays student details using a function with keyword
arguments has been executed successfully.

30
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
FUNCTIONS - VARIABLE LENGTH
4 f) POSITIONAL ARGUMENTS

AIM:

To write a python program that calculates the sum of given numbers using a function with
variable length positional arguments, and return value.

PROGRAM:
# Function that calculates the sum of multiple
numbers def calculate_sum(*numbers):
return sum(numbers)

# Calling the function with multiple or variable no. of arguments


print("Sum:", calculate_sum(5, 10, 15, 20))
print("Sum:", calculate_sum(1, 2, 3, 4, 5, 6))

OUTPUT:
After Calling the Function: 50

RESULT:
Thus the python program that calculates the sum of given numbers using a function with
variable length positional arguments, and return value has been executed successfully.

31
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
FUNCTIONS - VARIABLE LENGTH
4 g) KEYWORD ARGUMENTS

AIM:

To write a python program that displays employee details using a function with variable
length keyword arguments, and no return value.

PROGRAM:
# Function that prints employee
details def
employee_details(**details):
for key, value in [Link]():
print(f"{key}: {value}")

# Calling function with multiple keyword arguments


employee_details(name="Alice", age=25, department="HR", salary=50000)

OUTPUT:
Student Name: Alice
Age: 20
Course: Computer Science

RESULT:
Thus the python program that displays employee details using a function with variable
length keyword arguments, and no return value has been executed successfully.

32
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
FUNCTIONS - RECURSIVE FUNCTION
4 h)

AIM:

To write a python program that calculates the factorial of a given number using a recursive
function.

PROGRAM:
# Recursive function to calculate factorial
def factorial(n):
if n == 1:
return 1
else:

return n * factorial(n -
1) # Taking user input
num = int(input("Enter a number: "))
print(f"Factorial of {num} is:", factorial(num))

OUTPUT:
Enter a number: 5
Factorial of 5 is: 120

RESULT:
Thus the python program that calculates the factorial of a given number using a recursive
function has been executed successfully.

33
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
MODULES - USER DEFINED MODULE
4 i)

AIM:

To write a python program that creates a user defined module to find the area of shapes.

PROGRAM:

module_cal.py

def sq(a):
return
a*a def rect(w,l):
return w*l
def tri(h,b):
return (h*b)/2
def cir(r):
return 3.14*r*r

module_demo.py

import module_cal
a=int(input("Enter the Value of side:"))
w=int(input("Enter the Value of Width:"))
l=int(input("Enter the Value of Length:"))
h=int(input("Enter the value of Height:"))
b=int(input("Enter the value of Base:"))
r=int(input("Enter the Value of radius:"))

34
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
print("area of Square : ",module_cal.sq(a))
print("area of Rectangle :",module_cal.rect(w,l))
print("area of Triangle :",module_cal.tri(h,b))
print("area of Circle :",module_cal.cir(r))

OUTPUT:
Enter the Value of side:25
Enter the Value of Width:40
Enter the Value of Length:24
Enter the value of Height:12
Enter the value of Base:23
Enter the Value of radius:34
area of Square : 625
area of Rectangle : 960
area of Triangle :
138.0 area of Circle :
3629.84

RESULT:
Thus the python program that creates a user-defined module to find the area of shapes has
been executed successfully.
35
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
MODULES - MATH MODULE
4 j)

AIM:

To write a python program that demonstrates the use of the math module by performing
various mathematical operations.

PROGRAM:
import math
print("*****FACTORIAL*****")
a = int(input("enter the number:"))
print("the factorial of the given number is", [Link](a)) # returns factorial of the given
number
print("\n")
print("*****ABSOLUTE VALUE*****")
b = int(input("enter the number:"))
print("the absolute float value of the given number is", [Link](b)) # returns the absolute value
print("\n")
print("*****MODULUS*****")
x = int(input("enter the numerator:"))
y = int(input("enter the denominator:"))
print("the modulus of the given number is", [Link](x, y)) # Returns the remainder when x is
divided by y
print("\n")

print("*****SQUARE ROOT*****")
c = int(input("enter the number:"))
print("the squareroot of the given number is", [Link](c)) # returns the square root value

36
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
print("\n")
print("*****pi value*****")
r = int(input("enter the radius:"))
print("the area of the circle is", [Link] * r * r) # returns the pi value(3.14)
print("\n")
print("*****TRUNCATE*****")

d = float(input("enter the decimal number:"))


print("the truncate value of the given number is", [Link](d)) # returns the truncated integer
value
print("\n")
print("*****SIN*****")
e = int(input("enter the number:"))
print("the sine value of the given number is", [Link](e)) # returns the sine value
print("\n")
print("*****COS*****")
f = int(input("enter the number:"))
print("the cosine value of the given number is", [Link](f)) # returns the cosine
value print("\n")
print("*****TAN*****")
g = int(input("enter the number:"))
print("the tangent value of the given number is", [Link](g)) # returns the tangent value print("\
n")
print("*****INFINITY*****")
h = int(input("enter the number:"))
print("the given number is", [Link](h)) # returns True if the given number is a positive or
negative infinity

37
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
OUTPUT:
*****FACTORIAL*****
enter the number:6
the factorial of the given number is 720

*****ABSOLUTE
VALUE***** enter the
number:3
the absolute float value of the given number is 3.0

*****MODULUS*****
enter the numerator:5
enter the denominator:2
the modulus of the given number is 1.0

*****SQUARE ROOT*****
enter the number:2
the squareroot of the given number is 1.4142135623730951

*****pi value*****
enter the radius:1
the area of the circle is 3.141592653589793

*****TRUNCATE*****
enter the decimal number:1.34567
the truncate value of the given number is 1

*****SIN*****
enter the number:1
38
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
the sine value of the given number is 0.8414709848078965

*****COS*****
enter the number:90
the cosine value of the given number is -0.4480736161291701

*****TAN*****
enter the number:89
the tangent value of the given number is 1.6858253705060158

*****INFINITY*****
enter the number:0
the given number is False

RESULT:

Thus the python program that demonstrates the use of the math module by performing
various mathematical operations has been executed successfully.

39
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
MODULES - TIME MODULE
4 k)

AIM:

To write a Python program that demonstrates the use of the time module

PROGRAM:
import time #import the time
module print("*****TIME*****")
seconds = [Link]() #The time() function returns the number of seconds passed since epoch.
print("Seconds since epoch =", seconds)
print("\n")

print("*****CURRENT TIME*****")
local_time = [Link](seconds) #The [Link]() function takes seconds passed since epoch as
an argument and returns a string representing local time.
print("Local time:", local_time)
print("\n")
print("This is printed immediately.")
[Link](2.4) #The sleep() function suspends (delays) execution of the current thread for the
given number of seconds.
print("This is printed after 2.4
seconds.") print("\n")
print("*****LOCAL TIME*****")

result = [Link](seconds) #The localtime() function takes the number of seconds passed
since epoch as an argument and returns struct_time in local time.
print("result:", result) print("\
nyear:", result.tm_year)

40
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
print("tm_hour:", result.tm_hour)
print("\n")
print("*****TIME AND HOUR*****")
result = [Link](seconds) #The gmtime() function takes the number of seconds passed since
epoch as an argument and returns struct_time in UTC.
print("result:", result) print("\
nyear:", result.tm_year)
print("tm_hour:", result.tm_hour)
print("\n")
print("*****MAKE TIME*****")
t = (2018, 12, 28, 8, 44, 4, 4, 362, 0)

local_time = [Link](t) #The mktime() function takes struct_time (or a tuple containing
9 elements corresponding to struct_time) as an argument and returns the seconds passed
since epoch in local time. Basically, it's the inverse function of localtime().
print("Local time:",
local_time) print("\n")
print("*****TIME WITH DAY*****")
t = (2018, 12, 28, 8, 44, 4, 4, 362, 0)
result = [Link](t) #The asctime() function takes struct_time (or a tuple containing 9 elements
corresponding to struct_time) as an argument and returns a string representing it
print("Result:", result)

print("\n")

print("*****MONTH/DATE/YEAR*****")
named_tuple = [Link]() # get
struct_time
time_string = [Link]("%m/%d/%Y, %H:%M:%S", named_tuple)#The strftime() function takes
struct_time (or tuple corresponding to it) as an argument and returns a string representing it
based on the format code used.
print(time_string)
print("\n")
print("*****TIME AS STRUCTURE FORMAT*****")
41
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
time_string = "21 June, 2018"
result = [Link](time_string, "%d %B, %Y") #The strptime() function parses a string
representing time and returns struct_time.
print(result) print("\
n")

OUTPUT:

*****TIME*****
Seconds since epoch = 1583953676.6467428

*****CURRENT TIME*****

Local time: Thu Mar 12 00:37:56 2020


This is printed immediately.
This is printed after 2.4 seconds.
*****LOCAL TIME*****
result: time.struct_time(tm_year=2020, tm_mon=3, tm_mday=12, tm_hour=0,
tm_min=37, tm_sec=56, tm_wday=3, tm_yday=72, tm_isdst=0)

year: 2020
tm_hour: 0
*****TIME AND HOUR*****

result: time.struct_time(tm_year=2020, tm_mon=3, tm_mday=11, tm_hour=19,


tm_min=7, tm_sec=56, tm_wday=2, tm_yday=71, tm_isdst=0)
year: 2020
tm_hour: 19

*****MAKE TIME*****
Local time: 1545966844.0
*****TIME WITH DAY*****
Result: Fri Dec 28 08:44:04 2018

42
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
*****MONTH/DATE/YEAR*****
03/12/2020, 00:37:59
*****TIME AS STRUCTURE FORMAT*****
time.struct_time(tm_year=2018, tm_mon=6, tm_mday=21, tm_hour=0, tm_min=0,
tm_sec=0, tm_wday=3, tm_yday=172, tm_isdst=-1)

RESULT:
Thus the python program that demonstrates the use of the time module has been executed
successfully.

43
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
FILES CONCEPT - TEXT FILE
5 a)

AIM:
To write a python program to create a student record management system that uses a text
file to store student records.
PROGRAM:

# Function to display the


menu def display_menu():
print("\nStudent Records Management System")
print("1. View All Records")
print("2. Add Student Record")
print("3. Remove Student Record")
print("4. Exit")

# Function to view all student records in the file


def view_records(file_name):
try:
with open(file_name, 'r') as file:
records = [Link]()
if not records:
print("No records found.")
else:
print("\nStudent Records:")
for record in records:
print([Link]())

44
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
except FileNotFoundError:
print("No records found. Starting a new file.")

# Function to add a student record


def add_record(file_name):
student_name = input("Enter student's name:
") student_id = input("Enter student ID: ")
student_grade = input("Enter student's grade:
")

with open(file_name, 'a') as file: [Link](f"{student_name},


{student_id},{student_grade}\n")

print(f"Record for {student_name} added successfully.")

# Function to remove a student record


def remove_record(file_name):
try:
with open(file_name, 'r') as file:
records = [Link]()
if not records:

print("No records to remove.")


return
print("\nSelect the record to remove:")
for idx, record in enumerate(records,
1):
print(f"{idx}. {[Link]()}")

record_num = int(input("\nEnter the record number to remove:


45
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
")) if600004
1 <= record_num <= len(records):

46
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
removed_record = [Link](record_num - 1)
with open(file_name, 'w') as file:
[Link](records)
print(f"Record ( {removed_record.strip()} )removed.")
else:
print("Invalid record
number.") except FileNotFoundError:
print("No records to remove.")

# Main program loop


def main():
file_name = 'student_records.txt' # Text file where student records will be saved
while True:
display_menu()
choice = input("Select an option: ")

if choice == '1':
view_records(file_name)
elif choice == '2':
add_record(file_name)
elif choice == '3':
remove_record(file_name)
elif choice == '4':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please select a valid option.")

47
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
# Start the application
if name == " main ":
main()

OUTPUT:

Student Records Management System


1. View All Records
2. Add Student Record
3. Remove Student Record
4. Exit

Select an option: 1
No records found. Starting a new file.

Select an option: 2
Enter student's name: Guru
Enter student ID: 28
Enter student's grade: A
Record for Guru added successfully.

Select an option: 2

Enter student's name: John


Enter student ID: 44
Enter student's grade: C
Record for John added successfully.

Select an option: 1
Student Records:
Guru,28,A

48
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
John,44,C

Select an option: 3
Select the record to remove:
1. Guru,28,A

2. John,44,C
Enter the record number to remove: 2
Record for John,44,C removed.

Select an option: 1
Student Records:
Guru,28,A

Select an option: 4
Exiting the program. Goodbye!

RESULT:
Thus the python program to create a student record management system that uses a text
file to store student records has been executed successfully.

49
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
FILES CONCEPT - BINARY FILE
5 b)

AIM:
To write a python program to create a student record management system that uses a
binary file to store student records.
PROGRAM:

import pickle
# Function to add a new book to the library
def add_book(library):
title = input("Enter book title: ")
author = input("Enter author name:
") genre = input("Enter book genre:
") book = {
'title': title,
'author':
author, 'genre':
genre
}
[Link](book)
print(f"Book '{title}' added successfully.")

# Function to search for books by title


def search_by_title(library):
search_title = input("Enter title to search for: ")
found_books = [book for book in library if search_title.lower() in
book['title'].lower()] if found_books:
50
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
for book in found_books:
print(f"Title: {book['title']}, Author: {book['author']}, Genre:
{book['genre']}") else:
print(f"No books found with title containing '{search_title}'.")

# Function to search for books by author


def search_by_author(library):
search_author = input("Enter author name to search for: ")
found_books = [book for book in library if search_author.lower() in
book['author'].lower()] if found_books:
for book in found_books:
print(f"Title: {book['title']}, Author: {book['author']}, Genre: {book['genre']}")
else:
print(f"No books found by author '{search_author}'.")

# Function to display all books in the library


def display_books(library):
if not library:
print("No books in the library.")
else:
for idx, book in enumerate(library, 1):
print(f"{idx}. Title: {book['title']}, Author: {book['author']}, Genre: {book['genre']}")

# Function to save the library to a pickle file


def save_data(library):
with open('[Link]', 'wb') as
f: [Link](library, f)
print("Library data saved successfully.")

51
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

# Function to load the library from a pickle file


def load_data():
try:
with open('[Link]', 'rb') as
f: library = [Link](f)
return library
except FileNotFoundError:
print("No library data found. Starting with an empty library.")
return []

# Main function to run the application


def main():
library = load_data() # Load existing library data if available

while True:
print("\nBook Management System")
print("1. Add Book")
print("2. Search Book by Title")
print("3. Search Book by
Author") print("4. Display All
Books") print("5. Save Library
Data") print("6. Exit")
choice = input("Enter your choice: ")

if choice == '1':
add_book(library)
elif choice == '2':

52
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
search_by_title(library)
elif choice == '3':
search_by_author(library)
elif choice == '4':
display_books(library)
elif choice == '5':
save_data(library)
elif choice == '6':
print("Exiting the system.")
break
else:
print("Invalid choice. Please try again.")

if name == " main ":


main()

OUTPUT:
Book Management System
1. Add Book
2. Search Book by Title

3. Search Book by Author


4. Display All Books
5. Save Library Data
6. Exit

Enter your choice: 1


Enter book title: The Power of Your Subconscious
Mind Enter author name: Joseph Murphy

53
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Enter book genre: Self-Help and Spirituality
Book 'The Power of Your Subconscious Mind' added successfully.

Enter your choice: 1


Enter book title: The Psychology of Money:

Enter author name: Morgan Housel


Enter book genre: Business &
Economics
Book 'The Psychology of Money:' added successfully.

Enter your choice: 2

Enter title to search for: The Power of Your Subconscious Mind


Title: The Power of Your Subconscious Mind, Author: Joseph Murphy, Genre: Self-Help and
Spirituality

Enter your choice: 3


Enter author name to search for: Morgan Housel
Title: The Psychology of Money:, Author: Morgan Housel, Genre: Business & Economics

Enter your choice: 4


1. Title: The Power of Your Subconscious Mind, Author: Joseph Murphy, Genre: Self-Help
and Spirituality
2. Title: The Psychology of Money:, Author: Morgan Housel, Genre: Business & Economics

Enter your choice: 5


Library data saved successfully.

RESULT:
Thus the python program to create a student record management system that uses a
binary file to store student records has been executed successfully.
54
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
FILES CONCEPT - CSV FILE
5 c)

AIM:
To write a python program to create a student record management system that uses a csv
file to store student records.
PROGRAM:

import csv
# Function to add a new student
record def add_student(student_file):
name = input("Enter student's name:
") age = input("Enter student's age: ")
grade = input("Enter student's grade:
")

with open(student_file, mode='a', newline='') as file:


writer = [Link](file)
[Link]([name, age, grade])

print(f"Student {name} added successfully.")

# Function to display all students


def
display_students(student_file):
try:
with open(student_file, mode='r') as
file: reader = [Link](file)
55
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
students = list(reader)

56
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

if students: print("\
nStudent List:")
for idx, student in enumerate(students, 1):
print(f"{idx}. Name: {student[0]}, Age: {student[1]}, Grade:
{student[2]}") else:
print("No students found.")
except FileNotFoundError:
print("No student data found. The file is empty.")

# Function to update a student's


details def
update_student(student_file):
display_students(student_file) # Show students to the user
student_number = int(input("Enter the student number to update: ")) - 1

try:
with open(student_file, mode='r') as file:
reader = [Link](file)
students = list(reader)

if 0 <= student_number < len(students):


print(
f"Current details - Name: {students[student_number][0]}, Age:
{students[student_number][1]}, Grade: {students[student_number][2]}")
name = input("Enter new name (leave blank to keep current): ")
age = input("Enter new age (leave blank to keep current): ")
grade = input("Enter new grade (leave blank to keep current): ")

57
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
if name:

58
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
students[student_number][0] = name
if age:
students[student_number][1] = age
if grade:
students[student_number][2] = grade

# Writing the updated list back to the CSV file


with open(student_file, mode='w', newline='') as file:
writer = [Link](file)
[Link](students)

print("Student details updated successfully.")


else:
print("Invalid student number.")
except FileNotFoundError:
print("No student data found.")

# Function to delete a student record


def delete_student(student_file):
display_students(student_file) # Show students to the user
student_number = int(input("Enter the student number to delete: ")) - 1

try:
with open(student_file, mode='r') as file:
reader = [Link](file)
students = list(reader)

if 0 <= student_number < len(students):

59
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
del students[student_number]

# Writing the updated list back to the CSV file


with open(student_file, mode='w', newline='') as file:
writer = [Link](file)
[Link](students)

print("Student record deleted successfully.")


else:
print("Invalid student number.")
except FileNotFoundError:
print("No student data found.")

# Main function to run the application


def main():
student_file = '[Link]'

while True:
print("\nStudent Management System")
print("1. Add Student")
print("2. Display All Students")
print("3. Update Student Details")
print("4. Delete Student")
print("5. Exit")
choice = input("Enter your choice: ")

if choice == '1':
add_student(student_file)

60
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
elif choice == '2':
display_students(student_file)
elif choice == '3':
update_student(student_file)
elif choice == '4':
delete_student(student_file)
elif choice == '5':
print("Exiting the system.")
break
else:
print("Invalid choice. Please try again.")

if name == " main ":


main()

OUTPUT:
Student Management System
1. Add Student
2. Display All Students
3. Update Student Details

4. Delete Student
5. Exit

Enter your choice: 1

Enter student's name: Guru


Enter student's age: 20
Enter student's grade: A
Student Guru added successfully.

61
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

Enter your choice: 1


Enter student's name: Ram
Enter student's age: 22
Enter student's grade: C
Student Ram added successfully.

Enter your choice:


2 Student List:
1. Name: Guru, Age: 20, Grade: A

2. Name: Ram, Age: 22, Grade: C

Enter your choice:


3 Student List:
1. Name: Guru, Age: 20, Grade: A

2. Name: Ram, Age: 22, Grade: C


Enter the student number to update: 2
Current details - Name: Ram, Age: 22, Grade:
C Enter new name (leave blank to keep
current): Enter new age (leave blank to keep
current): 20 Enter new grade (leave blank to
keep current): Student details updated
successfully.

Enter your choice:


2 Student List:
1. Name: Guru, Age: 20, Grade: A
2. Name: Ram, Age: 20, Grade: C

62
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Enter your choice: 4 Student List:
1. Name: Guru, Age: 20, Grade: A
2. Name: Ram, Age: 20, Grade: C
Enter the student number to delete:
1 Student record deleted
successfully.

Enter your choice: 2


Student List:
1. Name: Ram, Age: 20, Grade: C

RESULT:
Thus the python program to create a student record management system that uses a csv file
to store student records has been executed successfully.

63
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex
No.
EXCEPTION HANDLING
5 d)

AIM:

To write a python program to implement exception handling concepts.

PROGRAM:

def handle_multiple_exceptions():
try:
num1 = int(input("Enter a number for integer conversion: "))

num2 = int(input("Enter another number for division: "))


result = num1 / num2
print(f"The result of {num1} / {num2} is: {result}")

with open("non_existent_file.txt", "r") as file:


content = [Link]()

my_list = [1, 2, 3]
print(my_list[5])

print(undefined_variable)

my_dict = {"name": "John"}


print(my_dict["age"])

invalid_int = int("hello")

my_str = "Hello"

my_str.append(" world") # Strings don't have append method

result2 = "string" + 5

except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid value entered.")
64
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
except FileNotFoundError:
print("Error: File not found.")
except IndexError:
print("Error: Index out of range in a list.")
except NameError:
print("Error: Variable is not defined.")
except KeyError:
print("Error: Key not found in the dictionary.")
except AttributeError:
print("Error: Invalid method or attribute for object.")
except TypeError:
print("Error: Unsupported operation between incompatible types.")
except Exception as e:
print(f"An unexpected error occurred: {e}")

handle_multiple_exceptions()

OUTPUT:
Enter a number for integer conversion: 10cm
Error: Invalid value entered.
Enter a number for integer conversion: 10
Enter another number for division: 0
Error: Cannot divide by zero.
Enter a number for integer conversion: 10
Enter another number for division: 2
The result of 10 / 2 is: 5.0
Error: File not found.
Error: Index out of range in a list.
Error: Variable is not defined.
Error: Key not found in the dictionary
Error: Invalid value entered.
Error: Invalid method or attribute for object.
Error: Unsupported operation between incompatible types.

RESULT:
Thus the python program to implement exception handling concepts has been executed
successfully.
65
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex No. CLASS AND OBJECTS
6

AIM:
To write a program that demonstrates class and objects to manage a bank account system.

PROGRAM:

# Class definition
class BankAccount:
"""A simple Bank Account class to manage deposits, withdrawals, and balance checks."""
def init (self, account_holder, balance=0):
"""Initialize account with holder's name and starting balance."""
self.account_holder = account_holder
[Link] = balance
def deposit(self, amount):
"""Deposit money into the
account."""
if amount > 0:

[Link] += amount
print(f"₹{amount} deposited successfully.")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
"""Withdraw money if there is enough balance."""
if amount > [Link]:
print("Insufficient
balance!") elif amount > 0:

66
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004 -= amount
[Link]

67
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
print(f"₹{amount} withdrawn successfully.")
else:
print("Withdrawal amount must be
positive.") def check_balance(self):
"""Check and display the current account balance."""
print(f"Available balance: ₹{[Link]}")
# Creating an account object
account = BankAccount("John Doe", 1000)
# Performing transactions
print("Bank Account Operations:")
account.check_balance() # Show initial balance
[Link](500) # Deposit money
account.check_balance() # Check balance after deposit
[Link](700) # Withdraw money
account.check_balance() # Check balance after
withdrawal
[Link](2000) # Try to withdraw more than balance

OUTPUT:
Bank Account Operations:
Available balance: ₹1000

₹500 deposited successfully.


Available balance: ₹1500
₹700 withdrawn successfully.
Available balance: ₹800
Insufficient balance!

RESULT:
Thus the python program that demonstrates class and objects to manage a bank account
68
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
system has600004
been executed successfully.

69
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

EX No. SINGLE INHERITANCE

7a)

AIM:
To write a python program that demonstrates single inheritance, where a Car class inherits
attributes and methods from a Vehicle class.

PROGRAM:
# Single Inheritance Example: Vehicle -> Car
class Vehicle:
“””Parent class representing a generic
vehicle.””” Def init (self, brand, speed):
[Link] = brand
[Link] = speed

def display_info(self):
print(f”Vehicle Brand: {[Link]}, Speed: {[Link]} km/h”)

class Car(Vehicle):

“””Child class inheriting from


Vehicle.””” Def honk(self):
print(“Car Honks: Beep Beep!”)

# Demonstration

print(“Single Inheritance Example:”)


car = Car(“Toyota”, 120)
car.display_info()

70
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
[Link]()

OUTPUT:
Single Inheritance Example:
Vehicle Brand: Toyota, Speed: 120 km/h
Car Honks: Beep Beep!

RESULT:
Thus the python program to demonstrate single inheritance has been executed successfully.

71
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

EX No. MULTIPLE INHERITANCE

7b)
AIM:

To write a Python program that demonstrates multiple inheritance, where a Manager class
inherits attributes and methods from both Employee and Leader classes.

PROGRAM:
# Multiple Inheritance Example: Employee + Leader -> Manager
class Employee:
“””Represents an employee with basic details.”””
Def init (self, name, salary):
[Link] = name
[Link] =
salary

def get_salary(self):
print(f”{[Link]}’s Salary: ₹{[Link]}”)

class Leader:
“””Represents a leadership role.”””
Def give_speech(self):
print(“Leader’s Speech: Motivating the team!”)

class Manager(Employee, Leader):


“””Inherits from both Employee and
Leader.””” Def manage_team(self):
print(f”{[Link]} is managing the team efficiently.”)

72
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
# Demonstration
print(“\nMultiple Inheritance Example:”)
manager = Manager(“Alice”, 75000)
manager.get_salary()
manager.give_speech()
manager.manage_team()

OUTPUT:
Multiple Inheritance Example:
Alice’s Salary: ₹75000

Leader’s Speech: Motivating the team!


Alice is managing the team efficiently.

RESULT:
Thus the python program to demonstrate multiple inheritance has been executed
successfully.

73
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

EX No. MULTILEVEL INHERITANCE

7c)

AIM:
To write a python program that demonstrates multilevel inheritance, where a Fixed Deposit
Account class inherits features from a Savings Account class, which in turn inherits from a Bank
Account class.

PROGRAM:
# Multilevel Inheritance Example: Bank Account -> Savings Account -> Fixed Deposit Account
class BankAccount:
"""Represents a basic bank account."""
def init (self, account_holder, balance):
self.account_holder = account_holder
[Link] = balance

def check_balance(self):
print(f"Account Holder: {self.account_holder}, Balance: ₹{[Link]}")

class SavingsAccount(BankAccount):

"""Inherits from BankAccount and adds interest feature."""


def add_interest(self, rate):
interest = [Link] * (rate /
100) [Link] += interest
print(f"Interest added: ₹{interest}, New Balance: ₹{[Link]}")

class FixedDepositAccount(SavingsAccount):

74
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
"""Inherits from SavingsAccount and adds fixed deposit feature."""
def lock_funds(self, years):
print(f"Funds locked for {years} years with a fixed interest rate.")

# Demonstration

print("\nMultilevel Inheritance Example:")


fd_account = FixedDepositAccount("John Doe", 10000)
fd_account.check_balance()
fd_account.add_interest(5) # 5% interest
fd_account.lock_funds(3) # 3-year fixed deposit

OUTPUT:
Multilevel Inheritance Example:
Account Holder: John Doe, Balance: ₹10000
Interest added: ₹500.0, New Balance: ₹10500.0
Funds locked for 3 years with a fixed interest rate.

RESULT:

Thus the python program to demonstrate multilevel inheritance has been executed
successfully.

75
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

EX No. HIERARCHICAL INHERITANCE

7d)

AIM:
To write a Python program that demonstrates hierarchical inheritance, where both Student
and Teacher classes inherit common properties and methods from the School class.

PROGRAM:
# Hierarchical Inheritance Example: School -> Student, Teacher
class School:
"""Parent class representing a school member."""
def init (self, name, age):
[Link] = name
[Link] = age

def show_details(self):
print(f"Name: {[Link]}, Age: {[Link]}")

class Student(School):

"""Inherits from School, representing a student."""


def study(self):
print(f"{[Link]} is studying.")

class Teacher(School):

"""Inherits from School, representing a teacher."""


def teach(self):
print(f"{[Link]} is teaching.")

76
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

# Demonstration
print("\nHierarchical Inheritance Example:")
student = Student("Bob", 16)
teacher = Teacher("Mr. Smith", 40)

student.show_details()
[Link]()

teacher.show_details()
[Link]()

OUTPUT:
Hierarchical Inheritance Example:
Name: Bob, Age: 16
Bob is studying.
Name: Mr. Smith, Age: 40
Mr. Smith is teaching.

RESULT:
Thus the python program to demonstrate hierarchical inheritance has been executed
successfully.

77
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

EX No. HYBRID INHERITANCE

7e)

AIM:
To write a Python program that demonstrates hybrid inheritance, where a Smartphone class
inherits attributes and methods from both Phone and Computer classes, forming a hybrid
structure.”

PROGRAM:
# Hybrid Inheritance Example: Device -> Phone + Computer -> Smartphone
class Device:
“””Base class representing an electronic device.”””
Def power_on(self):
print(“Device is now ON.”)

class Phone(Device):
“””Inherits from Device, representing a phone.”””
Def make_call(self, number):
print(f”Calling {number}…”)

class Computer(Device):
“””Inherits from Device, representing a computer.”””
Def browse_web(self):
print(“Browsing the web…”)

class Smartphone(Phone, Computer):


“""Hybrid Inheritance: Inherits from both Phone and Computer."""

78
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
def use_app(self, app_name):
print(f"Using the {app_name} app.")

# Demonstration

print("\nHybrid Inheritance Example:")


smartphone = Smartphone()
smartphone.power_on() # Inherited from
Device
smartphone.make_call("1234567890") # Inherited from Phone
smartphone.browse_web() # Inherited from Computer
smartphone.use_app("Instagram") # Unique to Smartphone

OUTPUT:
Hybrid Inheritance Example:
Device is now ON.
Calling 1234567890...
Browsing the web...
Using the Instagram
app.

RESULT:

79
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Thus the python program to demonstrate hybrid inheritance has been executed successfully.

80
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

EX No. FUNCTION OVERLOADING

8 a)

AIM:
To write a program to demonstrate function overloading.

PROGRAM:

# Function Overloading using Default


Arguments def greet(name="Guest",
age=None):
"""Greet the user with name and optionally age."""
if age:
print(f"Hello {name}, you are {age} years old!")
else:
print(f"Hello {name}!")

# Function Overloading using Variable-Length


Arguments def add_numbers(*args):
"""Add multiple numbers passed as arguments."""
return sum(args)
# Demonstration of Function Overloading
print("Function Overloading Examples:")
greet() # Default greeting
greet("Alice") # Passing only name
greet("Bob", 25) # Passing name and age

print(f"Sum of 10, 20: {add_numbers(10, 20)}")


81
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
print(f"Sum of 5, 10, 15, 20: {add_numbers(5, 10, 15, 20)}")

82
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

OUTPUT:
Function Overloading Examples:
Hello Guest!
Hello Alice!

Hello Bob, you are 25 years old!


Sum of 10, 20: 30
Sum of 5, 10, 15, 20: 50

RESULT:

Thus the python program to demonstrate function overloading has been executed
successfully.

83
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

EX No. FUNCTION OVERRIDING

8 b)

AIM:
To write a program to demonstrate function overriding.

PROGRAM:

# Function Overriding Example with


Inheritance class Parent:
"""Parent class with a method to display a message."""
def show_message(self):
print("This is the Parent class.")
class Child(Parent):
"""Child class overriding the method of Parent class."""
def show_message(self):
print("This is the Child class, overriding the Parent class method.")
# Demonstration of Function Overriding
print("Function Overriding Example:")
parent = Parent()
child = Child()
parent.show_message() # Calls Parent class method
child.show_message() # Calls overridden method in Child class

84
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
OUTPUT:
Function Overriding Example:
This is the Parent class.
This is the Child class, overriding the Parent class method.

RESULT:
Thus a python program to demonstrate function overriding has been executed successfully.

85
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex STUDENT RECORD MANAGEMENT SYSTEM
No.
(GUI PROGRAMMING)
9

AIM:

To write a python program to create a student record management system using tkinter.

PROGRAM:
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk

def add_student():

name = name_entry.get()
roll_no = roll_no_entry.get()
course =
course_combobox.get()
gender = "Male" if gender_var.get() else "Female"
payment_mode = payment_var.get()

if not name or not roll_no or not course or not gender or not payment_mode:
[Link]("Input Error", "Please fill in all fields.")
return

student_data = f"{name} - {roll_no} - {gender} - {course} - Payment: {payment_mode}"


student_listbox.insert([Link], student_data)
name_entry.delete(0, [Link])
roll_no_entry.delete(0, [Link])
86
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
gender_var.set(True)
payment_var.set(None)

def remove_student():
try:
selected_student = student_listbox.curselection()
student_listbox.delete(selected_student)
except IndexError:
[Link]("Selection Error", "Please select a student to remove.")
def update_student():
try:

selected_student_index = student_listbox.curselection()[0]
updated_name = name_entry.get()
updated_roll_no = roll_no_entry.get()
updated_course = course_combobox.get()
updated_gender = "Male" if gender_var.get() else
"Female" updated_payment_mode = payment_var.get()

if not updated_name or not updated_roll_no or not updated_course or not updated_gender or


not updated_payment_mode:
[Link]("Input Error", "Please fill in all fields.")
return

updated_student_data = f"{updated_name} - {updated_roll_no} - {updated_gender} -


{updated_course} - Payment: {updated_payment_mode}"
student_listbox.delete(selected_student_index)
student_listbox.insert(selected_student_index, updated_student_data)
name_entry.delete(0, [Link])
roll_no_entry.delete(0, [Link])

87
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
gender_var.set(True)
payment_var.set(None)
except IndexError:
[Link]("Selection Error", "Please select a student to update.")
root = [Link]()
[Link]("Student Information System")
[Link]("600x650")
title_label = [Link](root, text="Student Information System", font=("Arial", 18))
title_label.grid(row=0, column=0, columnspan=2, pady=10)
name_label = [Link](root, text="Student Name:", font=("Arial",
12)) name_label.grid(row=1, column=0, sticky="w", padx=10,
pady=5) name_entry = [Link](root, font=("Arial", 12))
name_entry.grid(row=1, column=1, pady=5)
roll_no_label = [Link](root, text="Roll Number:", font=("Arial",
12)) roll_no_label.grid(row=2, column=0, sticky="w", padx=10,
pady=5) roll_no_entry = [Link](root, font=("Arial", 12))
roll_no_entry.grid(row=2, column=1, pady=5)
course_label = [Link](root, text="Course:", font=("Arial", 12))
course_label.grid(row=3, column=0, sticky="w", padx=10, pady=5)
courses = ["Computer Science", "Electrical Engineering", "Mechanical Engineering", "Civil
Engineering", "Biotechnology"]
course_combobox = [Link](root, font=("Arial", 12), values=courses, state="readonly")
course_combobox.grid(row=3, column=1, pady=5)
course_combobox.set("Select a course")

gender_label = [Link](root, text="Gender:", font=("Arial", 12))


gender_label.grid(row=4, column=0, sticky="w", padx=10, pady=5)
gender_var = [Link]()

88
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
gender_checkbutton = [Link](root, text="Male/Female", variable=gender_var,
font=("Arial", 12))
gender_checkbutton.grid(row=4, column=1, pady=5)

payment_label = [Link](root, text="Mode of Payment:", font=("Arial", 12))


payment_label.grid(row=5, column=0, sticky="w", padx=10, pady=5)
payment_var = [Link]()
payment_radio1 = [Link](root, text="Cash", variable=payment_var, value="Cash",
font=("Arial", 12))
payment_radio1.grid(row=6, column=0, sticky="w", padx=10, pady=5)
payment_radio2 = [Link](root, text="Credit Card", variable=payment_var, value="Credit
Card", font=("Arial", 12))
payment_radio2.grid(row=6, column=1, pady=5)
payment_radio3 = [Link](root, text="Debit Card", variable=payment_var, value="Debit
Card", font=("Arial", 12))
payment_radio3.grid(row=7, column=0, sticky="w", padx=10, pady=5)
payment_radio4 = [Link](root, text="Online Payment", variable=payment_var,
value="Online Payment", font=("Arial", 12))

payment_radio4.grid(row=7, column=1, pady=5)


add_button = [Link](root, text="Add Student", font=("Arial", 12),
command=add_student) add_button.grid(row=8, column=0, columnspan=2, pady=10)

student_listbox = [Link](root, font=("Arial", 12), width=50,


height=10) student_listbox.grid(row=9, column=0, columnspan=2,
pady=10)

remove_button = [Link](root, text="Remove Selected Student", font=("Arial",


12), command=remove_student)
remove_button.grid(row=10, column=0, pady=5)

update_button = [Link](root, text="Update Selected Student", font=("Arial",


12), command=update_student)
89
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
update_button.grid(row=10, column=1, pady=5)

90
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
[Link]()

OUTPUT:

RESULT:
Thus the python program to create a student record management system using tkinter has
been executed successfully.

91
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex DESCRIPTIVE STATISTICS
No.
( MEAN, MEDIAN, MODE AND STANDARD
10 DEVIATION)

AIM:
To write a python program to calculate mean, median, mode and standard deviation for a given
list of numbers.

PROGRAM:
import statistics
def calculate_statistics(data):
mean = [Link](data)
median = [Link](data)
try:
mode = [Link](data)
except [Link]:
mode = "No unique mode"
std_dev = [Link](data)
return mean, median, mode,
std_dev

data = [int(x) for x in input("Enter numbers separated by spaces: ").split()]


mean, median, mode, std_dev = calculate_statistics(data)
print(f"Mean: {mean}")
print(f"Median: {median}")
print(f"Mode: {mode}")
print(f"Standard Deviation: {std_dev}")

92
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

OUTPUT:
Enter numbers separated by spaces: 18 20 21 19 24 25 26 17
Mean: 21.25
Median: 20.5

Mode: 18
Standard Deviation: 3.370036032024414

RESULT:
Thus the python program to calculate mean, median, mode and standard deviation for a
given list of numbers has been executed successfully.

93
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex No. CORRELATION
11 (YEARS OF EXPERIENCE VS SALARY)

AIM:
To write a python program to visualize and find the correlation between years of experience
and salary.

PROGRAM:
import pandas as pd
import [Link] as plt

def scatter_plot(x,y):
[Link](x, y)
[Link]('Scatter Plot')
[Link](VAR_NAMES[0])
[Link](VAR_NAMES[1])
[Link]()

def correlation(x,y):
cor_coeff = [Link](y, method='pearson')
print(f'Pearson correlation coefficient for {VAR_NAMES[0]} and {VAR_NAMES[1]}:
{cor_coeff}')

file_path = r"Z:\dataset\[Link]"
df = pd.read_csv(file_path)
X = df['years']
Y = df['salary']
VAR_NAMES = ["Years Of Experience","Salary"]

correlation(X,Y)
scatter_plot(X,Y)

94
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

OUTPUT:
Pearson correlation coefficient for Years Of Experience and Salary: 0.9782416184887597

RESULT:
Thus the python program to visualize and find the correlation of Years of Experience and
Salary has been executed successfully.

95
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex No. LINEAR REGRESSION
12 (SALARY ~ YEARS OF EXPERIENCE)

AIM:

To write a python program to apply a linear regression model for years of experience and
salary.

PROGRAM:

import pandas as pd
import numpy as np
from sklearn.linear_model import
LinearRegression import [Link] as plt

def apply_linear_reg(x,y):
global model
model = LinearRegression()
[Link](x, y)
slope = model.coef_
intercept =
model.intercept_
print(f"Coefficient (slope): {slope}")
print(f"Intercept: {intercept}")
print(f"Generated Model: y = {slope[0]}x + {intercept}")

def predict():
years_of_exp = float(input("Enter Your Years of Experience to predict the Salary: "))
y_pred = [Link]([Link](years_of_exp).reshape(-1, 1))
print("Predicted Salary: ", y_pred[0])

def visualize(x,y):
[Link](x, y, color='blue', label='Actual data')
[Link](x, [Link](x), color='red', label='Regression line')
[Link]('Linear Regression: Year of Experience vs Salary')
[Link]('Years of Experience')
[Link]('Salary (Predicted)')
[Link]()

96
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
[Link]()

97
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004

file_path = r"Z:\dataset\[Link]"
df = pd.read_csv(file_path)
X = df['years'].[Link](-1,1) # Independent variable
Y = df['salary'].values # Dependent variable

apply_linear_reg(X,Y)
predict()
visualize(X,Y)
OUTPUT:
Coefficient (slope): [9449.96232146]
Intercept: 25792.20019866871
Generated Model: y = 9449.962321455074x + 25792.20019866871
Enter Your Years of Experience to predict the Salary: 5.2
Predicted Salary: 74932.0042702351

RESULT:
Thus the python program to apply a linear regression model for years of experience and
salary has been executed successfully.

98
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex No. ANOVA – ONE WAY CLASSIFICATION
13 (EFFECTS OF FERTILIZERS ON
PLANTS)

AIM:
To write a Python program that uses one-way ANOVA to analyze whether fertilizers A, B, and
C have statistically significant effects.

PROGRAM:

import pandas as pd
import [Link] as sm
from [Link] import ols

ALPHA =0.05

def one_way_anova(df):
model = ols('height ~ C(fertilizer)', data=df).fit()
anova_table = [Link].anova_lm(model, typ=1) # Type 1
ANOVA print("ANOVA TABLE: ")
print(anova_table)
p_value = anova_table["PR(>F)"].iloc[0]

print("Conclusion: ", end="")


if p_value < ALPHA:
print("There is significant difference between fertilizers")
else:
print("There is no significant difference between fertilizers")

file_path = r"Z:\dataset\[Link]"
data = pd.read_excel(file_path)
one_way_anova(data)

99
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
OUTPUT:
ANOVA TABLE:
df sum_sq mean_sq F PR(>F)
C(fertilizer) 2.0 217.0 108.5 7.431507 0.005717
Residual 15.0 219.0 14.6 NaN NaN
Conclusion: There is significant difference between fertilizers

RESULT:

Thus the python program that uses one-way ANOVA to analyze whether fertilizer A, B and C
have statistically significant effects has been executed successfully.

100
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex No. ANOVA – TWO WAY CLASSIFICATION
14 ( FERTILIZERS AND WATERING SCHEDULE)

AIM:
To write a python program that performs two-way ANOVA to analyze whether Fertilizers (A, B,
C) and Watering Schedules (Daily, Weekly) have statistically significant effects, and to check for any
interaction between them.

PROGRAM:
import pandas as pd
import [Link] as sm
from [Link] import ols
ALPHA = 0.05

def two_way_anova(df):
model = ols('height ~ C(fertilizer) + C(watering) + C(fertilizer):C(watering)', data=df).fit()
anova_table = [Link].anova_lm(model, typ=2) # Type 2 ANOVA table
print("Two-Way ANOVA
Table:") print(anova_table)

fertilizer_p_value = anova_table["PR(>F)"].iloc[0]
watering_p_value = anova_table["PR(>F)"].iloc[1]
interaction_p_value =
anova_table["PR(>F)"].iloc[2]

print("\nConclusion:")
if fertilizer_p_value < ALPHA:
print("There is significant difference between fertilizer
types") else:
print("There is no significant difference between fertilizer types")

if watering_p_value < ALPHA:


print("There is significant difference between Watering Schedules")
else:
print("There is no significant difference between Watering

Schedules") if interaction_p_value < ALPHA:


101
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
print("There is significant interaction between fertilizer type and watering schedule")
else:
print("There is no significant interaction effect between fertilizer type and watering
schedule.")

file_path = r"Z:\dataset\[Link]"
data = pd.read_excel(file_path)
two_way_anova(data)

OUTPUT:

Two-Way ANOVA Table:


sum_sq df F PR(>F)

C(fertilizer) 217.0 2.0 108.5 2.070497e-08


C(watering) 200.0 1.0 200.0 7.606637e-09
C(fertilizer):C(watering) 7.0 2.0 3.5 6.346962e-02
Residual 12.0 12.0 NaN NaN

Conclusion:
There is significant difference between fertilizer types
There is significant difference between Watering Schedules
There is no significant interaction effect between fertilizer type and watering schedule.

RESULT:

Thus the python program that uses two-way ANOVA to analyze whether Fertilizers (A, B, C
and Watering Schedules (Daily, Weekly) have statistically significant effects has been executed
successfully.

102
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
Ex CHI-SQUARE TEST
No.
(GENDER AND MOVIE PREFERENCE)
15

AIM:
To write a Python program that uses the chi-square test to determine whether gender and
movie preferences are independent or related.
PROGRAM:
import numpy as np
import pandas as
pd
from [Link].contingency_tables import Table

ALPHA = 0.05

def chi_sq_test(observed_data):
table = Table(observed_data)
result = table.test_nominal_association()

chi2_stat = [Link]
p_value = [Link]
dof = [Link]
expected = [Link]

print(f"Chi-square Statistic: {chi2_stat:.2f}")


print(f"Degrees of Freedom: {dof}")
print("Expected Frequencies:")
print(expected)
print(f"P-value: {p_value:.5f}") print("\
nConclusion: ")
if p_value < ALPHA:
print("Gender and movie preference are related.")
else:
print("Gender and movie preference are independent.")

data = pd.read_excel(r"Z:\dataset\[Link]")

103
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
data = [Link][:,["action_movies","romantic_movies"]]
chi_sq_test(data)

OUTPUT:
Chi-square Statistic: 16.67
Degrees of Freedom: 1
Expected Frequencies:
action_movies romantic_movies

0 30.0 20.0
1 30.0 20.0

P-value: 0.00004

Conclusion:
Gender and movie preference are related.

RESULT:
Thus the python program that uses the chi-square test to determine whether gender and
movie preferences are independent or related has been executed successfully.

104
BCA IIIrd YEAR 2313281033020 MUKESH Y

You might also like