Python Lab
Python Lab
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
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.
AIM:
To write a python program to find the grade for a given mark using if..elif..else statement.
PROGRAM:
# Grading system
OUTPUT:
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: "))
4
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
OUTPUT:
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:
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:
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. "
11
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
print("Joining a list of words: "," ".join(words))
text_alpha = "Python"
text_digit = "12345"
text_alnum = "Python123"
# 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
# 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
15
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
# Count characters
vowels, consonants, whitespaces = count_characters(text)
OUTPUT:
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]
# 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)
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]
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:
[Link](num)
else:
[Link](num)
# print lists
OUTPUT:
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 with a comma after it won't be converted into integer
my_tuple = (100,)
print("With Comma, Result: ",my_tuple, " | Type: ", type(my_tuple) )
22
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
# nested tuple
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:
OUTPUT:
Enter your name: john
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:
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:
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}")
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)
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}")
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*****")
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*****
year: 2020
tm_hour: 0
*****TIME AND HOUR*****
*****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:
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.")
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.")
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:
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
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.")
51
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
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.")
OUTPUT:
Book Management System
1. Add Book
2. Search Book by Title
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.
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:
")
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.")
try:
with open(student_file, mode='r') as file:
reader = [Link](file)
students = list(reader)
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
try:
with open(student_file, mode='r') as file:
reader = [Link](file)
students = list(reader)
59
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
del students[student_number]
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.")
OUTPUT:
Student Management System
1. Add Student
2. Display All Students
3. Update Student Details
4. Delete Student
5. Exit
61
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
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.
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:
PROGRAM:
def handle_multiple_exceptions():
try:
num1 = int(input("Enter a number for integer conversion: "))
my_list = [1, 2, 3]
print(my_list[5])
print(undefined_variable)
invalid_int = int("hello")
my_str = "Hello"
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
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
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):
# Demonstration
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
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!”)
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
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
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):
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
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
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):
class Teacher(School):
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
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…”)
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
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
8 a)
AIM:
To write a program to demonstrate function overloading.
PROGRAM:
82
BCA IIIrd YEAR 2313281033020 MUKESH Y
Ramakrishna Mission Vivekananda College (Autonomous), Mylapore, Chennai -
600004
OUTPUT:
Function Overloading Examples:
Hello Guest!
Hello Alice!
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
8 b)
AIM:
To write a program to demonstrate function overriding.
PROGRAM:
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
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()
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")
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)
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
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]
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")
file_path = r"Z:\dataset\[Link]"
data = pd.read_excel(file_path)
two_way_anova(data)
OUTPUT:
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]
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