CS Practical with Algorithm and Result
CS Practical with Algorithm and Result
DATE :
AIM:
To compute the Fibonacci series for a given number of terms using a user-defined
function in Python.
ALGORITHM:
Step 1: Open IDLE and create a new file.
Step 2: Start program by declaring user defined function by using def.
Step 3: Use for loop to calculate the next Fibonacci number using a, b = b, a + b
Step 4: Using input() function get number of terms from the user.
Step 5: Call the function using a given input as an argument.
SOURCE CODE:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" , ")
a, b = b, a + b
# Input: number of terms
num_terms = int(input("Enter the number of terms: "))
fibonacci(num_terms)
OUTPUT:
Enter the number of terms: 11
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 ,
RESULT:
Thus, to compute the Fibonacci series for a given number of terms using a user-
defined function in Python has been done successfully.
EXP NO :2
DATE :
CALCULATE FACTORIAL
AIM:
To calculate the factorial of given ‘n’ numbers using a user-defined function in
Python.
ALGORITHM:
Step 1: Open IDLE and create a new file
Step 2: Start program by declaring user defined function using def.
Step 3: Use if condition to calculate the factorial of nth number.
Step 4: Use input() function to get input from the user.
Step 5: Call the function with given input as an argument.
SOURCE CODE:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
n = int(input("Enter a number to compute factorial: "))
print(factorial(n))
OUTPUT:
Enter a number to compute factorial: 8
40320
RESULT:
Thus, to calculate the factorial of given ‘n’ numbers using a user-defined function in Python
has been done successfully.
EXP NO :3
DATE :
PALINDROME CHECK
AIM:
To check if the entered string is a palindrome or not in Python.
ALGORITHM:
Step 1: Open IDLE and create a new file.
Step 2: Start program by declaring user defined function using def.
Step 3: Use list operation to reverse the given string and check whether the reversed
string matches the given string.
Step 4: Use if condition and confirm the given string is a palindrome or not.
Step 5: Use input() function to get string from the user.
Step 6: Call the function using the input as an argument.
SOURCE CODE:
def is_palindrome(s):
return s == s[::-1]
s = input("Enter a string: ")
print("Palindrome:", s[::-1])
print(is_palindrome(s))
if is_palindrome(s):
print(f'{s[::-1]} is a Palindrome of {s}')
else:
print(f'{s[::-1]} is not a Palindrome of {s}')
OUTPUT:
Enter a string: malayalam
Palindrome: malayalam
True
malayalam is a Palindrome of malayalam
RESULT:
Thus, to check if the entered string is a palindrome or not in Python has been done
successfully.
EXP NO :4
DATE :
AIM:
To compute prime numbers between 2 to n in Python.
ALGORITHM:
Step 1: Open IDLE and create a new file.
Step 2: Start program by declaring user defined function using def.
Step 3: Use input() function to get the end range from the user.
Step 4: Use for loop and find the remainder of the given number by dividing it using the
numbers greater than 2.
Step 5: If the number has divisors beyond 1 and itself then it’s not a prime number.
Step 6: Call the function to execute the program.
SOURCE CODE:
def prime():
start = 2
end = int(input("Enter the end range number: "))
for i in range(start, end+1):
is_prime = True
for j in range(2, int(i**0.5) + 1):
if i % j == 0:
is_prime = False
break
if is_prime and i > 1:
print(i)
prime()
OUTPUT:
Enter the end range number: 15
2
3
5
7
11
13
RESULT:
Thus, computing the prime numbers between 2 to n in Python has been done successfully.
EXP NO :5
DATE :
SIN(X, N) APPROXIMATION
AIM:
To compute the sin(x, n) function using a mathematical approximation in Python.
ALGORITHM:
Step 1: Open IDLE And create a new file.
Step 2: Start program by importing “math” module to perform mathematical operations.
Step 3: Declare user defined function using def.
Step 4: Use for loop and find the sign(x.n) approximation and return the value.
Step 5: Use input() function to get value for x and n.
Step 6: Call the user defined function with values of x and n as an argument.
SOURCE CODE:
import math
def sin(x, n):
s=0
for i in range(n):
sign = (-1) ** i
pi = 22 / 7
y = x * (pi / 180) # Change from 80 to 180 to convert degrees to radians
s += (y ** (2 * i + 1)) / math.factorial(2 * i + 1) * sign
return s
x = int(input("Enter the value of x (degree): "))
n = int(input("Enter the value of n: "))
print(round(sin(x, n), 2))
OUTPUT:
Enter the value of x (degree): 28
Enter the value of n: 3
0.47
RESULT:
Thus, to compute the sin(x, n) function using a mathematical approximation in Python has
been done successfully.
EXP NO :6
DATE :
LIST SORTING
AIM:
To perform insertion sorting in a list in Python.
ALGORITHM:
Step 1: Open IDLE and create a new file.
Step 2: Create a sequence of numbers as a list.
Step 3: Use for loop with range from one to length of the list.
Step 4: Rearrange the list by sorting the numbers in ascending order.
Step 5: Print the newly sorted list.
SOURCE CODE:
lst = [10, 5, 18, 12, 4, 6]
print("Original list:", lst)
for i in range(1, len(lst)):
key = lst[i]
j=i-1
while j >= 0 and key < lst[j]:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key
print("List after insertion sort:", lst)
OUTPUT:
Original list: [10, 5, 6, 12, 4, 18]
List after insertion sort: [4, 5, 6, 10, 12, 18]
RESULT:
Thus, to perform insertion sorting in a list in Python has been done successfully.
EXP NO :7
DATE :
AIM:
To remove duplicate values from list in Python.
ALGORITHM:
Step 1: Open IDLE and create a new file.
Step 2: Start the program by getting input from the user using input() method to create a
list.
Step 3: Using for loop check for duplicate entries in the list.
Step 4: Using append() method add elements to the new list by removing duplicates.
Step 5: Now print the new list after removing the duplicates.
SOURCE CODE:
a = eval(input("Enter list: "))
n = []
for i in a:
if i not in n:
n.append(i)
print(n)
OUTPUT:
Enter list: [4,5,6,7,8,4,5,3,2]
[4, 5, 6, 7, 8, 3, 2]
RESULT:
Thus, removing duplicate values from list in Python has been done successfully.
EXP NO :8
DATE :
AIM:
To compute the sum of all numbers in a list in Python.
ALGORITHM:
Step 1: Open IDLE and create a new file.
Step 2: Start the program by declaring user defined function using def.
Step 3: Use input() method to get the number of elements to be stored in the list.
Step 4: Use for loop to get the elements from the user, append the elements to the list
and find the sum by calling the user defined function.
SOURCE CODE:
def findSum(lst, num):
if num == 0:
return 0
else:
return lst[num - 1] + findSum(lst, num - 1)
mylist = []
num = int(input("Enter how many numbers: "))
for i in range(num):
n = int(input("Enter Element " + str(i + 1) + ": "))
mylist.append(n)
sum = findSum(mylist, len(mylist))
print("Sum of List items ", mylist, " is: ", sum)
OUTPUT:
Enter how many numbers: 7
Enter Element 1: 6
Enter Element 2: 5
Enter Element 3: 3
Enter Element 4: 8
Enter Element 5: 9
Enter Element 6: 66
Enter Element 7: 9
Sum of List items [6, 5, 3, 8, 9, 66, 9] is: 106
RESULT:
Thus, to compute the sum of all numbers in a list in Python has been done successfully.
EXP NO :9
DATE :
AIM:
To import a user-defined module into a Python program.
ALGORITHM:
Step 1: Open IDLE and create a new file to create a user defined module.
Step 2: Use the def keyword and create two user defined functions to find the area of
square and rectangle.
Step 3: Create a new file and use import keyword to import the previous file as a
module.
From <filename> import <function name>
Step 4: Call the function of user defined module using the function name.
SOURCE CODE:
sqrec.py
def square():
num = int(input("Enter size square in cm: "))
area = num * num
print("Area of square: ", area, " sqcm")
return area
def rect():
length = int(input("Enter length of rectangle in cm: "))
breadth = int(input("Enter breadth of rectangle in cm: "))
area = length * breadth
print("Area of rectangle: ", area, " sqcm")
return area
usermodule.py
from sqrect import square, rect
# Call the functions from the imported user module
square()
rect()
OUTPUT:
Enter size square in cm: 5
Area of square: 25 sqcm
Enter length of rectangle in cm: 9
Enter breadth of rectangle in cm: 3
Area of rectangle: 27 sqcm
RESULT:
Thus, importing a user-defined module into a Python program has been done successfully.
EXP NO : 10
DATE :
AIM:
To read a text file line by line and display each word separated by a ‘#’ in Python.
ALGORITHM:
Step 1: Create text file readme.txt having some content.
Step 2: Open IDLE and create a new file.
Step 3: Start the program by declaring user defined function using def.
Step 4: Use open() to open the text file in read mode.
Step 5: Use split() method to split the content word by word and use join() method to
add the separator to the content.
Step 6: Print, the content and use close() method to close the file.
SOURCE CODE:
def read_file(filename):
try:
rfile = open(filename, 'r')
for line in rfile:
words = line.split()
print('#'.join(words))
file.close()
except FileNotFoundError:
print(f"The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
read_file("readme.txt")
readme.txt
Fun Fact 1
There's a poem called the Zen of Python that can be read by writing import this in the
Interpreter.
Fun Fact 2
Python was released in 1991, while Java was released in 1995, making Python older than
Java.
OUTPUT:
Fun#Fact#1
There's#a#poem#called#the#Zen#of#Python#that#can#be#read#by#writing#import#this#in#t
he#Interpreter.
Fun#Fact#2
Python#was#released#in#1991,#while#Java#was#released#in#1995,#making#Python#older#
than#Java.
RESULT:
Thus, to read a text file line by line and display each word separated by a ‘#’ in Python has
been done successfully.
EXP NO : 11
DATE :
AIM:
To read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file using Python.
ALGORITHM:
Step 1: Open IDLE and create a new file.
Step 2: Use open() function to open readme.txt in read mode.
Step 3: Using read() method to read the content of text file and use islower() method to
count the lower case and isupper() method to count upper case in it.
Step 4: Create a list of vowels and consonants and check their presence on the content
and count the numbers.
Step 5: Close the file using close() method and print the counts of vowels, consonants,
uppercase and lowercase.
SOURCE CODE:
file = open("readme.txt", "r")
content = file.read()
vowels = 0
consonants = 0
lowercase = 0
uppercase = 0
nums=0
for ch in content:
if ch.islower():
lowercase += 1
elif ch.isupper():
uppercase += 1
ch = ch.lower()
if ch in ['a', 'e', 'i', 'o', 'u']:
vowels += 1
elif ch in ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']:
consonants += 1
if ch.isdigit():
nums+=1
file.close()
print("Total No of Character: ",len(content.replace(" ", "")))
print("No of Vowels are: ", vowels)
print("No of Consonants are: ", consonants)
print("No of Lowercase letters: ", lowercase)
print("No of Uppercase letters: ", uppercase)
print("No of Numbers: ", nums)
readme.txt
Fun Fact 1
There's a poem called the Zen of Python that can be read by writing import this in the
Interpreter.
Fun Fact 2
Python was released in 1991, while Java was released in 1995, making Python older than
Java.
OUTPUT:
Total No of Character: 178
No of Vowels are: 56
No of Consonants are: 103
No of Lowercase letters: 147
No of Uppercase letters: 12
No of Numbers: 10
RESULT:
Thus, to read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file using Python have been done successfully.
EXP NO : 12
DATE :
AIM:
To remove all lines containing the character 'a' in a text file and write the result to
another file in Python.
ALGORITHM:
Step 1: Create a text file “input.txt” having some content in it.
Step 2: Open IDLE and create a new file.
Step 3: Start the program by declaring user defined function using def.
Step 4: Use open() method to open the text file in read mode.
Step 5: Use for loop to find whether the character “a” or “A” present in the line or not.
Step 6: Using open() method open “output.txt” file in write mode so that it creates a
new file if does not exist.
Step 7: Write the line that does not contain character “a” or “A” to “output.txt” file.
Step 8: Use close() to close “input.txt” and “output.txt” files.
SOURCE CODE:
def rewrite(input_file, output_file):
try:
infile = open(input_file, 'r')
outfile = open(output_file, 'w')
for line in infile:
if 'a' not in line and 'A' not in line:
outfile.write(line)
print(f"Lines without 'a' have been written to '{output_file}'.")
except FileNotFoundError:
print(f"The file '{input_file}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
infile.close()
outfile.close()
rewrite("input.txt", "output.txt")
input.txt
A for Apple
B for Ball
C for Cat
One
Two
Three
OUTPUT:
Lines without 'a' have been written to 'output.txt'.
output.txt
One
Two
Three
RESULT:
Thus, to remove all lines containing the character 'a' in a text file and write the result to
another file in Python has been done successfully.
EXP NO : 13
DATE :
AIM:
To create a binary file with roll number, name, and marks in Python using list and
dictionary.
ALGORITHM:
Step 1: Open IDLE and create a new file
Step 2: Import “pickle” library to perform binary operations (serialization and
deserialization).
Step 3: Create a nested list having role no, name and mark values as each list.
Step 4: Also create a nested dictionary with role no as a key for each dictionary in it.
Step 5: Use with open() method to open the binary file in wb+ (write & read binary)
mode.
Step 6: Use pickle.dump() and pickle.load() method to write and read binary files.
Step 7: We don’t need to close the file manually because with open() method will
automatically close the file.
SOURCE CODE:
import pickle
students_list = [ [101, "Ari Kumar", 85] , [102, "Muthal Raj", 90] , [103, "Shaik", 78] ]
with open("students_list.bin", "wb+") as file:
pickle.dump(students_list, file)
file.seek(0)
data=pickle.load(file)
print("Data written to students_list.bin as a list. ", data)
students_dict = {
101: {"name": "Ari Kumar", "marks": 85},
102: {"name": "Muthal Raj", "marks": 90},
103: {"name": "Shaik", "marks": 78}
}
with open("students_dict.bin", "wb+") as file:
pickle.dump(students_dict, file)
file.seek(0)
data=pickle.load(file)
print("\nData written to students_dict.bin as a dictionary. ", data)
OUTPUT:
Data written to students_list.bin as a list. [[101, 'Ari Kumar', 85], [102, 'Muthal Raj', 90],
[103, 'Shaik', 78]]
Data written to students_dict.bin as a dictionary. {101: {'name': 'Ari Kumar', 'marks': 85},
102: {'name': 'Muthal Raj', 'marks': 90}, 103: {'name': 'Shaik', 'marks': 78}}
RESULT:
Thus, to create a binary file with roll number, name, and marks in Python using list and
dictionary has been done successfully.
EXP NO : 14
DATE :
AIM:
To search for a given roll number in a binary file and display the corresponding name
and mark, if not found display appropriate message.
ALGORITHM:
Step 1: Open IDLE and create a new file
Step 2: Import “pickle” library to perform binary operations (serialization and
deserialization).
Step 3: Declare user defined function using def.
Step 4: Use open() to open binary file in rb (read binary) mode.
Step 5: Use pickle.load() to read the binary file content to a local variable as a
dictionary.
Step 6: Use input() method to get the input from the user and to search on binary file.
Step 7: Now search by using the input as a key from the loaded dictionary.
Step 8: Use close() method to close an opened file.
SOURCE CODE:
import pickle
def search_student(filename, roll_number):
try:
file = open(filename, "rb")
students_dict = pickle.load(file)
if roll_number in students_dict:
student = students_dict[roll_number]
print(f"Roll Number: {roll_number}")
print(f"Name: {student['name']}")
print(f"Marks: {student['marks']}")
else:
print(f"Roll number {roll_number} not found.")
except FileNotFoundError:
print(f"The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
file.close()
filename = "students_dict.bin"
roll_number = int(input("Enter roll number to search: "))
search_student(filename, roll_number)
OUTPUT:
Enter roll number to search: 102
Roll Number: 102
Name: Muthal Raj
Marks: 90
RESULT:
Thus, to search for a given roll number in a binary file and display the corresponding name
and mark, if not found display appropriate message has been done successfully.
EXP NO : 15
DATE :
AIM:
To input a roll number and update the marks in a binary file using Python.
ALGORITHM:
Step 1: Open IDLE and create a new file
Step 2: Import “pickle” library to perform binary operations (serialization and
deserialization).
Step 3: Declare user defined function using def.
Step 4: Use open() method to open binary file in rb+ (read and write binary) mode.
Step 5: Load the file content using pickle.load() and store in a variable as a dictionary.
Step 6: Using if condition search for the value to be changed and change the value in
the dictionary.
Step 7: Using pickle.dump() rewrite the changed dictionary to the binary file.
Step 8: Close the file using close() and call the function for execution.
SOURCE CODE:
import pickle
def update_marks(filename, roll_number, new_marks):
try:
file = open(filename, "rb+")
students_dict = pickle.load(file)
if roll_number in students_dict:
students_dict[roll_number]['marks'] = new_marks
print(f"Updated marks for roll number {roll_number} to {new_marks}.")
file.seek(0)
pickle.dump(students_dict, file)
file.truncate()
else:
print(f"Roll number {roll_number} not found in the file.")
except FileNotFoundError:
print(f"The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
file.close()
filename = "students_dict.bin"
roll_number = int(input("Enter roll number to update: "))
new_marks = int(input("Enter new marks: "))
update_marks(filename, roll_number, new_marks)
OUTPUT:
Enter roll number to update: 102
Enter new marks: 99
Updated marks for roll number 102 to 99.
RESULT:
Thus, to input a roll number and update the marks in a binary file using Python has been done
successfully.
EXP NO : 16
DATE :
AIM:
To write a random number generator that generates random numbers between 1 and
6 (simulates some dice).
ALGORITHM:
Step 1: Open IDLE and create a new file.
Step 2: Use import keyword to import “random” library to the program.
Step 3: Use random.randint() function to get random integer for the given range.
Step 4: Using the while loop repeat the process until the user stops it.
SOURCE CODE:
import random
c = 'y'
b=6
while c == 'y':
a = random.randint(1, b)
print(a)
c = input("Roll the dice again (y/n): ")
OUTPUT:
1
Roll the dice again (y/n): y
6
Roll the dice again (y/n): y
2
Roll the dice again (y/n): y
5
Roll the dice again (y/n): n
RESULT:
Thus, to write a random number generator that generates random numbers between 1 and
6 (simulates some dice) has been done successfully.
EXP NO : 17
DATE :
STACK IMPLEMENTATION
AIM:
To write a Python program to implement a stack using list.
ALGORITHM:
Step 1: Open IDLE and create a new file.
Step 2: Declare an empty stack and create a function in the name of push(), pop() and
display() using def.
Step 3: In push() function use append() method to add element at last index.
Step 4: In pop() function use pop() method to remove the last index element.
Step 5: In display() function using if condition print the elements of stack, if the stack is
empty display a message “Stack Empty”.
Step 6: Print the choice and get the input from the user. Now call the decide function
according to the user choice.
SOURCE CODE:
stack = []
def push():
a = int(input("Enter the element to push into stack: "))
stack.append(a)
return a
def pop():
if stack == []:
print("Stack empty… underflow case… cannot delete the element")
else:
print("Deleted element is:", stack.pop())
def display():
if stack == []:
print("Stack empty… no elements")
else:
for i in range(len(stack) - 1, -1, -1):
print(stack[i])
print("STACK OPERATION")
print("***************************************")
choice = "y"
while choice == "y":
print("1. PUSH")
print("2. POP")
print("3. DISPLAY ELEMENTS OF STACK")
print("***************************************")
c = int(input("Enter the choice: "))
if c == 1:
push()
elif c == 2:
pop()
elif c == 3:
display()
else:
print("Wrong input")
choice = input("Do you want to continue (y/n): ")
OUTPUT:
STACK OPERATION
***************************************
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 3
Stack empty… no elements
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 1
Enter the element to push into stack: 30
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 1
Enter the element to push into stack: 25
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 1
Enter the element to push into stack: 35
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 2
Deleted element is: 35
1. PUSH
2. POP
3. DISPLAY ELEMENTS OF STACK
***************************************
Enter the choice: 3
25
30
Do you want to continue (y/n): n
RESULT:
Thus, to write a Python program to implement a stack using list has been done successfully.
EXP NO : 18
DATE :
AIM:
To create a CSV file by entering user-id and password, read and search the password
for given userid in Python.
ALGORITHM:
Step 1: Open IDLE and create a new file.
Step 2: Import “csv” module to perform CSV file operations.
Step 3: Declare insert_record() function using def to add data to csv file.
Step 4: Get username and password from the user, using input() and create a list with it.
Step 5: Using csv.writer() and write.writerows() methods to write the list to CSV file.
Step 6: Now declare search_record() function .
Step 7: Use csv.reader() method to read the content of CSV file to the nested list.
Step 8: Display choices to user for insert record and search record. Get the choice as
input from the user.
Step 9: According to the user choice call the desired functions.
SOURCE CODE:
import csv
def insert_record():
with open("data.csv", "a", newline='') as file:
writer = csv.writer(file)
writer.writerow(["UserName","Password"])
repeat = int(input("How many IDs do you wish to enter: "))
count = 0
credentials = []
while count < repeat:
uid = input("User Name: ")
pwd = input("Password: ")
credentials.append([uid, pwd])
count += 1
writer.writerows(credentials)
print("Records have been added successfully.")
def search_record(userid):
found = False
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
if row[0] == userid:
print(f'User Name : {row[0]}\nPassword : {row[1]}')
found = True
break
if not found:
print(f"The given User Name '{userid}' not found.")
option = int(input("1. Insert Record\n2. Search Record\nEnter your option: "))
if option == 1:
insert_record()
elif option == 2:
uid = input("Enter the User Name to search: ")
search_record(uid)
else:
print("Invalid Option")
OUTPUT:
1. Insert Record
2. Search Record
Enter your option: 1
How many IDs do you wish to enter: 3
User Name: muthal
Password: raj
User Name: vijay
Password: antony
User Name: harris
Password: jayaraj
Records have been added successfully.
1. Insert Record
2. Search Record
Enter your option: 2
Enter the User Name to search: muthal
User Name : muthal
Password : raj
RESULT:
Thus, to create a CSV file by entering user-id and password, read and search the
password for given userid in Python has been done successfully.
EXP NO : 19
DATE :
AIM:
To understand and perform operations of Data Definition Language (DDL) in SQL,
including creating a database, creating a table within the database, altering the table structure,
and dropping the table and database.
ALGORITHM:
Step 1: Open XAMPP control panel and start Apache web server and MySQL database.
Step 2: Go to SQL tab to write and execute SQL queries.
Step 3: Use “CREATE DATABASE” to create a database, use “CREATE TABLE” to
create a data table
Step 4: Use “DESCRIBE” command to get the structure of the table.
Step 5: To change the structure of the table use “ALTER TABLE” command.
Step 6: For deleting the database or table use “DROP DATABASE” or “DROP
TABLE” respectively.
QUERIES:
CREATE DATABASE School;
SHOW DATABASES;
USE School;
CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(50), Age
INT, Grade CHAR(1) );
DESCRIBE Students;
ALTER TABLE Students ADD COLUMN Address VARCHAR(100);
ALTER TABLE Students DROP COLUMN Address;
ALTER TABLE Students DROP PRIMARY KEY;
ALTER TABLE Students ADD PRIMARY KEY(StudentID);
DROP TABLE Students;
DROP DATABASE School;
OUTPUT:
Database
auction
information_schema
mysql
performance_schema
phpmyadmin
school
studentdb
test
Field Type Null Key Default Extra
StudentID int(11) NO PRI NULL
Name varchar(50) YES NULL
Age int(11) YES NULL
Grade char(1) YES NULL
RESULT:
Thus, to understand and perform operations of Data Definition Language (DDL) in
SQL, including creating a database, creating a table within the database, altering the table
structure, and dropping the table and database has been done successfully.
EXP NO : 20
DATE :
AIM:
To understand and perform operations of Data Manipulation Language (DML) in
SQL, including inserting, selecting, updating, and deleting data within a database table.
ALGORITHM:
Step 1: Open XAMPP control panel and start Apache web server and MySQL database.
Step 2: Go to SQL tab to write and execute SQL queries.
Step 3: To insert values to database use, “INSERT INTO” command.
Step 4: To retrieve data from database table use “SELECT” command.
Step 5: For updating any domain value on the table use the UPDATE command.
Step 6: To delete the particular or all tuple of the table use DELETE command.
QUERIES:
CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(50), Age
INT, Grade CHAR(1) );
INSERT INTO Students (StudentID, Name, Age, Grade) VALUES (1, 'Muthal', 17, 'A');
INSERT INTO Students (StudentID, Name, Age, Grade) VALUES (2, 'Raj', 16, 'B');
INSERT INTO Students (StudentID, Name, Age, Grade) VALUES (3, 'Raja', 17, 'A');
SELECT * FROM Students;
SELECT Name, Grade FROM Students;
SELECT * FROM Students WHERE Grade = 'A';
UPDATE Students SET Age = 16 WHERE Name = 'Raja';
DELETE FROM Students WHERE StudentID = 3;
OUTPUT:
SELECT * FROM Students;
StudentID Name Age Grade
1 Muthal 17 A
2 Raj 16 B
3 Raja 17 A
Raj B
Raja A
3 Raja 17 A
After UPDATE Students SET Age = 16 WHERE Name = 'Raja';
StudentID Name Age Grade
1 Muthal 17 A
2 Raj 16 B
3 Raja 16 A
RESULT:
Thus, to understand and perform operations of Data Manipulation Language (DML) in SQL,
including inserting, selecting, updating, and deleting data within a database table has been
done successfully.
EXP NO : 21
DATE :
CLAUSES IN SQL
AIM:
To understand clauses in SQL like DISTINCT, WHERE, IN, BETWEEN, ORDER
BY, NULL, GROUP BY, and HAVING using SELECT command.
ALGORITHM:
Step 1: Open XAMPP control panel and start Apache web server and MySQL database.
Step 2: Go to SQL tab to write and execute SQL queries.
Step 3: Use “SELECT” command to execute the SQL clauses and get output.
Step 4: Use “DISTINCT” to removes duplicate records, “WHERE” to filters records based
on conditions, “IN” to specifies multiple possible values, “BETWEEN” to selects
values within a range, “ORDER BY” to sorts the result set, “NULL” to represents
the absence of a value, “GROUP BY” to group records of same values in specified
columns and “HAVING” to filter groups based on conditions.
QUERIES:
SELECT DISTINCT Age FROM Students;
SELECT * FROM Students WHERE Age > 18;
SELECT * FROM Students WHERE Age IN (18, 19, 20);
SELECT * FROM Students WHERE Age BETWEEN 18 AND 25;
SELECT * FROM Students ORDER BY Name ASC;
SELECT * FROM Students WHERE Email IS NULL;
SELECT Age, COUNT(*) AS TotalStudents FROM Students GROUP BY Age;
SELECT Age, COUNT(*) AS TotalStudents FROM Students GROUP BY Age HAVING
COUNT(*) > 1;
OUTPUT:
StudentID Name Age Grade Email
1 Muthal 17 A muthalrajvj@example.com
2 Raj 16 B NULL
4 Sri Gopal 20 B NULL
5 Sudha 22 A sudha@example.com
6 Mathan 19 B NULL
7 Abhinaya 20 C abhinaya@example.com
8 Akshara 18 A aksara@example.com
RESULT:
Thus, to understand clauses in SQL like DISTINCT, WHERE, IN, BETWEEN, ORDER BY,
NULL, GROUP BY, and HAVING using SELECT command has been done successfully.
EXP NO : 22
DATE :
AIM:
To understand and implement equi-joins in SQL, allowing retrieval of related data
from multiple tables based on a common attribute.
ALGORITHM:
Step 1: Open XAMPP control panel and start Apache web server and MySQL database.
Step 2: Go to SQL tab to write and execute SQL queries.
Step 3: Use “JOIN” keyword to join column (attribute) of two tables “Students” and
“Enrollments”.
Step 4: Use “ON” keyword to cheque equality condition.
Step 5: To be particular, mention the column names with reference to table like
tablename.columnname.
QUERIES:
SELECT Students.Name, Enrollments.Course FROM Students JOIN Enrollments ON
Students.StudentID = Enrollments.StudentID;
Table: Students
StudentID Name Age Grade Email
1 Muthal 17 A muthalrajvj@example.com
2 Raj 16 B NULL
3 Sudha 22 A sudha@example.com
4 Sri Gopal 20 B NULL
5 Akshara 18 A aksara@example.com
6 Mathan 19 B NULL
7 Abhinaya 20 C abhinaya@example.com
Table: Enrollments
EnrollmentID StudentID Course
101 1 Mathematics
102 2 Science
103 1 English
104 3 Computer
105 2 Physics
106 5 Chemistry
107 6 Biology
108 7 Marketing
109 3 Business
110 5 Tamil
OUTPUT:
Name Course
Muthal Mathematics
Raj Science
Muthal English
Sudha Computer
Raj Physics
Akshara Chemistry
Mathan Biology
Abhinaya Marketing
Sudha Business
Akshara Tamil
RESULT:
Thus, to understand and implement equi-joins in SQL, allowing retrieval of related data from
multiple tables based on a common attribute has been done successfully.
EXP NO : 23
DATE :
AIM:
To execute aggregate functions (COUNT, SUM, AVG, MAX, MIN) using SELECT
command in SQL.
ALGORITHM:
Step 1: Open XAMPP control panel and start Apache web server and MySQL database.
Step 2: Go to scale tab to write and execute SQL queries.
Step 3: Use “SELECT” command to execute the aggregate functions in SQL and get
output.
Step 4: Use “COUNT” to count the number of rows, use “SUM” to calculate the sum,
use “AVG” to find the average value, “MAX” to find the maximum value and
“MIN” to find the minimum value.
QUERIES:
SELECT COUNT(*) AS TotalStudents FROM Students;
SELECT AVG(Age) AS AverageAge FROM Students;
SELECT MAX(Age) AS MaxAge FROM Students;
SELECT MIN(Age) AS MinAge FROM Students;
SELECT Sum(Age)/COUNT(Age) AS AverageAge FROM Students;
SELECT Grade, COUNT(*) AS CountPerGrade FROM Students GROUP BY Grade;
OUTPUT:
SELECT COUNT(*) AS TotalStudents FROM Students;
TotalStudents
7
RESULT:
Thus, executing aggregate functions (COUNT, SUM, AVG, MAX, MIN) using SELECT
command in SQL has been done successfully.
EXP NO : 24
DATE :
AIM:
To interface with a MySQL database and display all records from a table using
Python, by using the mysql.connector library.
ALGORITHM:
Step 1: Open XAMPP control panel and start Apache Server on MySQL database.
Step 2: Open IDLE and create a new file.
Step 3: Import mysql.connector Library to the program.
Step 4: Using def declare a function display_records() and use
mysql.connector.connect() to connect python program with MySQL database.
Step 5: Use cursor execute method to execute MySQL queries through python.
Step 6: Using cursor.fetchall() method retrieve the result of SQL queries.
Step 7: Using for loop print the result table row by row.
Step 8: Close the cursor and connection respectively.
SOURCE CODE:
import mysql.connector
def display_records():
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
if connection.is_connected():
print("Connected to the database.")
cursor = connection.cursor()
query = "SELECT * FROM students;"
cursor.execute(query)
records = cursor.fetchall()
print("Displaying all records from the students table:")
print(f"StudentID\tName\t\tAge\tGrade\tEmail")
for row in records:
print(f"{row[0]}\t\t{row[1]}\t\t{row[2]}\t{row[3]}\t{row[4]}")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
display_records()
OUTPUT:
Connected to the database.
Displaying all records from the students table:
StudentID Name Age Grade Email
1 Muthal 17 A muthalrajvj@example.com
2 Raj 16 B None
3 Sudha 22 A sudha@example.com
4 Sri Gopal 20 B None
5 Akshara 18 A aksara@example.com
6 Mathan 19 B None
7 Abhinaya 20 C abhinaya@example.com
Database connection closed.
RESULT:
Thus, to interface with a MySQL database and display all records from a table using Python,
by using the mysql.connector library has been done successfully.
EXP NO : 25
DATE :
AIM:
To delete a specific record from a table in MySQL using Python, by using the
mysql.connector library.
ALGORITHM:
Step 1: Open XAMPP control panel and start Apache Server on MySQL database.
Step 2: Open IDLE and create a new file.
Step 3: Import mysql.connector library to the program.
Step 4: Using Def Declare a function to the program delete_record() and use
mysql.connector.connect() to connect python with MySQL database.
Step 5: Use cursor.execute() method to execute MySQL queries through python.
Step 6: Using connection.commit() method execute the “DELETE” command.
Step 7: Close the cursor and connection respectively.
Step 8: Now call delete_record() function by providing value studentid which to be
deleted, as an argument.
SOURCE CODE:
import mysql.connector
def delete_record(student_id):
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
if connection.is_connected():
print("Connected to the database.")
cursor = connection.cursor()
query = "DELETE FROM students WHERE StudentID = %s"
cursor.execute(query, (student_id,))
connection.commit()
if cursor.rowcount > 0:
print(f"Record with StudentID {student_id} deleted successfully.")
else:
print(f"No record found with StudentID {student_id}.")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
student_id = int(input("Enter the StudentID of the record to delete: "))
delete_record(student_id)
OUTPUT:
Enter the StudentID of the record to delete: 6
Connected to the database.
Record with StudentID 6 deleted successfully.
Database connection closed.
RESULT:
Thus, to delete a specific record from a table in MySQL using Python, by using the
mysql.connector library has been done successfully.
EXP NO : 26
DATE :
AIM:
To fetch the first three records from a table in MySQL using Python, by using the
mysql.connector library.
ALGORITHM:
Step 1: Open XAMPP control panel and start Apache Server on MySQL database.
Step 2: Open IDLE and create a new file.
Step 3: Import mysql.connector library to the program.
Step 4: Using def declare a function fetch_first_three_records() and use
mysql.connector.connect() to connect python program with MySQL database.
Step 5: Use cursor.execute() method to execute MySQL queries through python.
Step 6: Using cursor.fetchall() method retrieve the result of SQL queries.
Step 7: Using for loop print the result table row by row.
Step 8: Close the cursor and connection respectively.
SOURCE CODE:
import mysql.connector
def fetch_first_three_records():
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
if connection.is_connected():
print("Connected to the database.")
cursor = connection.cursor()
query = "SELECT * FROM students LIMIT 3;"
cursor.execute(query)
records = cursor.fetchall()
print("Displaying the first three records from the students table:")
print(f"StudentID\tName\t\tAge\tGrade\tEmail")
for row in records:
print(f"{row[0]}\t\t{row[1]}\t\t{row[2]}\t{row[3]}\t{row[4]}")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
fetch_first_three_records()
OUTPUT:
Connected to the database.
Displaying the first three records from the students table:
StudentID Name Age Grade Email
1 Muthal 17 A muthalrajvj@example.com
2 Raj 16 B None
3 Sudha 22 A sudha@example.com
Database connection closed.
RESULT:
Thus, to fetch the first three records from a table in MySQL using Python, by using the
mysql.connector library has been done successfully.
EXP NO : 27
DATE :
AIM:
To insert a new record into a MySQL table using Python, by using the
mysql.connector library.
ALGORITHM:
Step 1: Open XAMPP control panel and start Apache Server on MySQL database.
Step 2: Open IDLE and create a new file.
Step 3: Import mysql.connector library to the program.
Step 4: Using def declare a function insert_record() with StudentID, Name, Age, Grade
and Email as a parameter.
Step 5: Use mysql.connector.connect() to establish connection with MySQL database.
Step 6: Use cursor.execute() to execute the “INSERT” query.
Step 7: Close the cursor and connection respectively.
Step 8: Use input() to get input values from the user.
Step 9: Call the function using user given values for StudentID, Name, Age, Grade and
Email as an argument to the function.
SOURCE CODE:
import mysql.connector
def insert_record(student_id, name, age, grade, email):
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
if connection.is_connected():
print("Connected to the database.")
cursor = connection.cursor()
query = "INSERT INTO students (StudentID, Name, Age, Grade, Email) VALUES
(%s, %s, %s, %s, %s)"
values = (student_id, name, age, grade, email)
cursor.execute(query, values)
connection.commit()
print(f"Record inserted successfully with StudentID {student_id}.")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("Database connection closed.")
student_id = int(input("Enter StudentID: "))
name = input("Enter Name: ")
age = int(input("Enter Age: "))
grade = input("Enter Grade: ")
email = input("Enter Email (or 'None' if not available): ")
email = None if email.lower() == "none" else email
insert_record(student_id, name, age, grade, email)
OUTPUT:
Enter StudentID: 6
Enter Name: Mathan
Enter Age: 19
Enter Grade: B
Enter Email (or 'None' if not available): None
Connected to the database.
Record inserted successfully with StudentID 6.
Database connection closed.
RESULT:
Thus, to insert a new record into a MySQL table using Python, by using the mysql.connector
library has been done successfully.