personal file 2.0

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

CENTRAL BOARD OF SECONDARY EDUCATION

( C.B.S.E )

SESSION: 2024-25
OF
COMPUTER SCIENCE (083)

PROGRAMS IN
CONCEPT OF PYTHON AND SQL

SUBMITTED TO: SUBMITTED BY:


MRS. ANITA SINGH NAME : YASH LATHER
GRADE : 12TH
ROLL NO : 30
CERTIFICATE
This is to certify that

"YASH LATHER
Student of Class
XII-B COMMERCE
has successfully completed their
COMPUTERS Pracital File
On
"CONCEPTS OF PYTHON
AND SQL"
Under the guidence of
"MRS. ANITA SINGH"

INTERNAL PRINCIPAL EXTERNAL


EXAMINER EXAMINER
INDEX
CLASS-XII
Sr. Name of practical Date Teacher's
no. Signature
1. Table of a number
2. Factorial of a number
3. Arithmetic operations on two numbers
4. Check string for palindrome
5. No. of terms in Fibonacci Series
6. Perform linear search on given list
7. Perform selection sort on given list
8. Perform binary search sort on given list
9. Creation of a text file
10. Read file in multiple ways
11. Searching for a specific word in a file
12. Count no. of lower case and uppercase
letters in a file
13. Write multiple lines to a text file
14. Connect to MySQL database with python
15. Perform all actions on a table with
MySQL-Python
#1 Program to print the table of a number
Sol:
def table(n):
print("Table of number")
for i in range(1,11):
print(n, "*", i, "=", n*i)
n = int(input("Enter any number"))
table(n)
OUTPUT
#2 Program to print the factorial of a number
Sol:
def fact(n):
factorial = 1
for i in range(1, n+1):
factorial = factorial*i
print("Factorial of number", n, "is", factorial)
n = int(input("Enter any number"))
fact(n)
OUTPUT
#3 Program to perform chosen arithmetic operation
on two numbers
Sol:
result = 0
val1 = float(input("Enter the first value :"))
val2 = float(input("Enter the second value :"))
op = input("Enter any one of the operator (+,-,*,/,//,%)")
if op == "+":
result = val1 + val2
elif op == "-":
result = val1 - val2
elif op == "*":
result = val1 * val2
elif op == "/":
if val2 == 0:
print("Please enter a value other than 0")
else:
result = val1 / val2
elif op == "//":
result = val1 // val2
else:
result = val1 % val2
print("The result is :",result)

OUTPUT
#4 Program to find if a string is a palindrome or not
Sol:
def isPalindrome(str):
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
inputString = input("enter any string: ")
result = isPalindrome(inputString)
if (ans):
print("Yes, it is a palindrome")
else:
print("No, not a palindrome")

OUTPUT
#5 Program to print the terms of Fibonacci series to
a limit
Sol:
limit =int(input("enter the limit:"))
x=0
y=1
z=1
print("Fibonacci series \n")
print(x, y, end= " ")
while(z<= limit):
print(z, end=" ")
x=y
y=z
z=x+y

OUTPUT
#6 Program to perform linear search on list
Sol:
def linear_Search(list1, n, key):
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9, 7]
key = 7
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
OUTPUT
#7 Program to perform selection sort on list
Sol:
def selectionSort(array, size):
for i in range(size):
min_index = i
for j in range(i+ 1, size):
if array[j] < array[min_index]:
min_index = j
(array[i], array[min_index]) = (array[min_index], array[i])
arr = [-29, -29, 42, 59, 69, 49, 79]
size = len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)
OUTPUT
#8 Program to perform binary search on list
Sol:
arr = [1,2,3,4,5,6,7,8,9,10]
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0

while low <= high:


mid = (high + low) // 2
if list1[mid] < n:
low = mid + 1
elif list1[mid] > n:
high = mid - 1
else:
return mid
return -1
n = int(input("enter no. to find"))
result = binary_search(arr, n)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in arr")

OUTPUT
#9 Creation of a text file using python
Sol:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:


f = open("demofile3.txt", "r")
print(f.read())
OUTPUT
#10 Read a text file in multiple way using python
Sol:
file1 = open("demofile3.txt", "r+")

print("Output of Read function is ")


print(file1.read())
print()

# seek(0) takes the file handle to the first line


file1.seek(0)

print("Output of Readline function is ")


print(file1.readline())
print()

file1.seek(0)

print("Output of Read(9) function is ")


print(file1.read(9))
print()

file1.seek(0)

print("Output of Readline(9) function is ")


print(file1.readline(9))

file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
OUTPUT

#11 Search for a specific word in a file


Sol:
fp = open('demofile3.txt', 'r')
# read all lines using readlines()
lines = fp.readlines()
for row in lines:
word = 'London'
if row.find(word) != -1:
print('string exists in file')
print('line Number:', lines.index(row))

OUTPUT
#12 Count no. of uppercase and lowercase letters
Sol:
def count_case_in_file():
with open("demofile3.txt", 'r') as file:
content = file.read()
# Initialize counters
uppercase_count = sum(1 for char in content if
char.isupper())
lowercase_count = sum(1 for char in content if
char.islower())

return uppercase_count, lowercase_count

uppercase, lowercase = count_case_in_file()

if uppercase is not None and lowercase is not None:


print(f"Number of uppercase letters: {uppercase}")
print(f"Number of lowercase letters: {lowercase}")
OUTPUT
#13 Write multiple line to a file
Sol:
num_lines = int(input("Enter the number of lines to write: "))
file_name = "output.txt"

with open(file_name, "w") as file:


for i in range(1, num_lines + 1):
line = f"Writing line no. {i}\n"
file.write(line)

print(f"Successfully written {num_lines} lines to {file_name}.")


OUTPUT
#14 Connect to a MySQL database with python
Sol:
import mysql.connector
from mysql.connector import Error
from dotenv import load_dotenv
import os

load_dotenv() # Load variables from .env file


mysql_password = os.getenv('MYSQL_PASSWORD')
try:
# Establish the connection
connection = mysql.connector.connect(
host='localhost',
database='demo_database',
user='root',
password=mysql_password
)
if connection.is_connected():
print("Connected to MySQL server")
Fetch server information
db_info = connection.get_server_info()
print("MySQL server version:", db_info)
# Create a cursor and execute a query
cursor = connection.cursor()
cursor.execute("SELECT DATABASE();")
record = cursor.fetchone()
print("Connected to database:", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
OUTPUT

#15 Perform all the operations with reference to


table ‘Employee’ through MySQL-Python
connectivity.
Sol:
# CREATION OF A TABLE
import mysql.connector
from mysql.connector import Error
from dotenv import load_dotenv
import os

load_dotenv() # Load variables from .env file


mysql_password = os.getenv('MYSQL_PASSWORD')

try:
# Establish the connection
connection = mysql.connector.connect(
host='localhost',
database='demo_database',
user='root',
password=mysql_password
)
if connection.is_connected():
print("Connected to MySQL server")
# Create a cursor object
cursor = connection.cursor()
# SQL statement to create a table
create_table_query = """
CREATE TABLE EMP(
empno integer primary key,
ename varchar(25) not null,
salary float
);
"""
# Execute the query
cursor.execute(create_table_query)
print("Table 'employees' created successfully!")

except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
OUTPUT

# INSERTING DATA TO A TABLE


try:
# Establish the connection
connection = mysql.connector.connect(
host='localhost',
database='demo_database',
user='root',
password=mysql_password
)
if connection.is_connected():
print("Connected to MySQL server")
# Create a cursor object
cursor = connection.cursor()
# SQL statement to create a table
insert_query = """
INSERT INTO EMP VALUES (
2,
'KADAMBDI SHARMA',
96000
);
"""
# Execute the query
cursor.execute(insert_query)
# Commit the transaction
connection.commit()
print("Dummy record inserted successfully!")

except Error as e:
print("Error while connecting to MySQL", e)
if connection.is_connected():
connection.rollback()
print("Transaction rolled back!")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
OUTPUT
# UPDATING RECORD(S) OF A TABLE USING
UPDATE
try:
# Establish the connection
connection = mysql.connector.connect(
host='localhost',
database='demo_database',
user='root',
password=mysql_password
)
if connection.is_connected():
print("Connected to MySQL server")
# Create a cursor object
cursor = connection.cursor()
# SQL statement to create a table
update_query = """
UPDATE EMP SET salary = salary +1000 WHERE
salary<100000;
"""
# Execute the query
cursor.execute(update_query)
# Commit the transaction
connection.commit()
print("Record updated successfully!")

except Error as e:
print("Error while connecting to MySQL", e)
if connection.is_connected():
connection.rollback()
print("Transaction rolled back!")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
OUTPUT
#DELETE RECORD(S) FROM A TABLE
try:
# Establish the connection
connection = mysql.connector.connect(
host='localhost',
database='demo_database',
user='root',
password=mysql_password
)
if connection.is_connected():
print("Connected to MySQL server")
# Create a cursor object
cursor = connection.cursor()
# SQL statement to create a table
delete_query = """
DELETE FROM EMP
WHERE salary < 90000;
"""
# Execute the query
cursor.execute(delete_query)
# Commit the transaction
connection.commit()
print("Record deleted successfully!")

except Error as e:
print("Error while connecting to MySQL", e)
if connection.is_connected():
connection.rollback()
print("Transaction rolled back!")
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
OUTPUT

You might also like