1
Index
Sr no. Program Page no
1 Checking for Palindrome word 1
2 Sorting list without using sort function 2
3 Inserting an Element in a List 3
4 Prime Number Check 4
5 Generate a Multiplication Table 5
6 Check if a Number is Armstrong 6
7 Find the Factorial of a Number 7
8 Calculate the Sum of Digits of a Number 8
9 Check if a Number is Perfect 9
10 Check if a Number is Perfect square 10
11 Choice-Based Stack Program 11
12 Function-Based Text File Program 13
13 Binary File Program 15
14 CSV File Program 17
15 Exception Handling Program 19
16 Creating a table and Inserting data 20
17 Updating data in a table 21
18 Using WHERE clause to select data 21
19 Deleting data 22
1
20 Using BETWEEN in a WHERE clause 22
21 write a code for creating a python program to 23
integrate MySQL with python with searching
and
displaying records
22 write a code for creating a python program to 24
integrate MySQL with python for updating
records
23 write a code for creating a python program to 26
integrate MySQL with python to write queries for
the following questions based on the given table
24 write a code for creating a python program to 27
integrate MySQL with python to write queries for
the following questions based on the given table
25 write a code for creating a python program to 28
integrate MySQL with python to Write a Query
to add a new column Area of type varchar in
table
STU from above table
1
1) Check for Palindrome:
a = "reviver"
is_palindrome =
True
for i in range(len(a) // 2):
if a[i] != a[len(a) - i -
1]: is_palindrome =
False break
if is_palindrome:
print(f"'{a}' is a
palindrome") else:
print(f"'{a}' is not a palindrome")
output:
1
1
1
2) Sorting list without using sort function:
a = [64, 25, 12, 22, 11]
for i in range(len(a)):
min_index = i
for j in range(i + 1, len(a)):
if a[j] < a[min_index]:
min_index = j
a[i], a[min_index] = a[min_index], a[i]
print("Sorted array:", a)
output:
2
1
3) Inserting an Element in a Sorted List:
a = [1, 2, 4, 5, 6]
b = 3
for i in
range(len(a)): if
b < a[i]:
a.insert(i,b)
break
else:
a.append(new_element)
print("Updated list:", a)
output:
1
3
1
4) Prime Number Check:
num = int(input("Enter number: "))
is_prime = True
if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
else:
is_prime = False
if is_prime:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
output:
4
1
5) Generate a Multiplication Table:
num = 7
limit = 10
print(f"Multiplication Table for {num}:")
for i in range(1, limit + 1):
print(f"{num} x {i} = {num * i}")
output:
5
1
6) Check if a Number is Armstrong:
def is_armstrong(num):
num_str = str(num)
n = len(num_str)
total = sum(int(digit) ** n for digit in num_str)
return total == num
num = 153
if is_armstrong(num):
print(f"{num} is an Armstrong number")
else:
print(f"{num} is not an Armstrong number")
output:
6
1
7) Find the Factorial of a Number:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
num = 5
print(f"Factorial of {num} is {factorial(num)}")
output:
7
1
8) Calculate the Sum of Digits of a Number:
def sum_of_digits(num):
total = 0
while num > 0:
total += num % 10
num //= 10
return total
number = 12345
print(f"Sum of digits of {number} is {sum_of_digits(number)}")
output:
8
1
9) Check if a Number is Perfect:
def is_perfect_number(n):
divisors_sum = 0
for i in range(1, n):
if n % i == 0:
divisors_sum += i
return divisors_sum == n
num = 28
if is_perfect_number(num):
print(f"{num} is a perfect number")
else:
print(f"{num} is not a perfect number")
output:
9
1
10) Check if a Number is Perfect square:
def is_perfect_square(n):
root = int(n ** 0.5)
return root * root == n
num = 49
if is_perfect_square(num):
print(f"{num} is a perfect square")
else:
print(f"{num} is not a perfect square")
output:
10
1
11) Choice-Based Stack Program:
stack = []
def push():
element = int(input("Enter element to push: "))
stack.append(element)
print(f"{element} pushed to stack")
def pop():
if not stack:
print("Stack is empty!")
else:
popped_element = stack.pop()
print(f"{popped_element} popped from stack")
def display():
if not stack:
print("Stack is empty!")
else:
print("Stack elements:", stack)
while True:
print("\n1. Push\n2. Pop\n3. Display\n4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
push()
elif choice == 2:
pop()
elif choice == 3:
display()
elif choice == 4:
break
else:
print("Invalid choice, please try again.")
11
1
output:
12
1
12) Function-Based Text File Program:
def count_words(filename):
try:
with open(filename, 'r') as file:
text = file.read()
words = text.split()
word_count = {}
for word in words:
word = word.lower()
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
except FileNotFoundError:
return "File not found!"
filename = "example.txt"
word_count =
count_words(filename) if
isinstance(word_count, dict):
print("Word counts:", word_count)
1
13
1
else:
print(word_count)
output:
14
1
13) Binary File Program:
Import pickle
def write_binary_file(filename, data):
with open(filename, 'wb') as file:
pickle.dump(data, file)
print(f"Data written to {filename}")
def read_binary_file(filename):
try:
with open(filename, 'rb') as file:
data = pickle.load(file)
return data
except FileNotFoundError:
return "File not found!"
numbers = [10, 20, 30, 40, 50]
filename = "numbers.dat"
write_binary_file(filename, numbers)
result = read_binary_file(filename)
if isinstance(result, list):
print("Data read from file:", result)
else:
print(result)
15
1
output:
16
1
14) CSV File Program:
import csv
def write_csv_file(filename, data):
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerows(data)
print(f"Data written to {filename}")
def read_csv_file(filename):
try:
with open(filename, mode='r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
print("File not found!")
data = [
["Alice", 24, "New York"],
["Bob", 27, "Los Angeles"],
["Charlie", 22, "Chicago"]
]
filename = "people.csv"
write_csv_file(filename, data)
print("\nReading CSV file:")
read_csv_file(filename)
17
1
output:
18
1
15) Exception Handling Program:
def divide_numbers(a, b):
try:
result = a / b
print(f"The result of {a} / {b} is {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")
except TypeError:
print("Error: Invalid input type! Please enter numbers.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
a = int(input("Enter the numerator: "))
b = int(input("Enter the denominator: "))
divide_numbers(a, b)
output:
19
1
16) Creating a table and Inserting data:
USE bot;
CREATE TABLE Students (
ID INT,
Name VARCHAR(50),
Age INT
);
INSERT INTO Students (ID, Name, Age) VALUES (1, 'John', 20);
INSERT INTO Students (ID, Name, Age) VALUES (2, 'Emma', 22);
INSERT INTO Students (ID, Name, Age) VALUES (3, 'Alex', 21);
SELECT * FROM Students;
output:
20
1
17) updating data:
USE bot;
UPDATE Students SET Age = 23 WHERE Name = 'Emma';
SELECT * FROM Students;
output:
18) Using WHERE clause to select data:
USE bot;
SELECT Name, Age FROM Students WHERE Age > 20;
output:
21
1
19) Deleting data:
USE bot;
DELETE FROM Students WHERE ID = 3;
SELECT * FROM Students;
output:
20) Using BETWEEN in a WHERE clause:
USE bot;
SELECT Name, Age FROM Students WHERE Age BETWEEN 20 AND 22;
output:
22
1
21) write a code for creating a python program to integrate
MySQL with python with searching and displaying records:
Execution:
Output:
23
1
22) write a code for creating a python program to integrate
MySQL with python for updating records:
Execution:
24
1
Output:
25
1
23) write a code for creating a python program to integrate MySQL
with python to write queries for the following questions based on
the given table:
Write a Query to select distinct Department from STU table.
SELECT DISTICT(DEPT) FROM STU;
Output:
26
1
24) write a code for creating a python program to integrate MySQL
with python to write queries for the following questions based on
the given table:
Write a Query to delete the details of Roll number is 8.
DELETE FROM STU WHERE ROLLNO=8;
Output:
27
1
25- write a code for creating a python program to integrate MySQL
with python to Write a Query to add a new column Area of type
varchar in table STU from above table
ALTER TABLE STU ADD AREA VARCHAR (20);
Output:
28