C5 python programs final
C5 python programs final
OR
n=int(input("Enter a number"))
digits=[]
while(n!=0):
digits.append(n%10)
n//=10
digits.reverse()
words=("Zero","One","Two","Three","Four","Five","Six","Seven","Eight",
"Nine")
for i in digits:
print(words[i],end=" ")
str=input("Enter a sentence")
vowels="aeiou"
cons="bcdfghijklmnpqrstvwxyz"
digits="0123456789"
splchars="!@#$%^&*+-*/\'\""
vcnt=ccnt=dcnt=scnt=0
for x in str:
if x.lower() in vowels:
vcnt+=1
if x.lower() in cons:
ccnt+=1
if x in digits:
dcnt+=1
if x in splchars:
scnt+=1
sentence=input("Enter a sentence")
lst=sentence.split()
word=input("enter a word to search")
if word in lst:
print("The word is found")
else:
print("Word not found")
6. Read a list of numbers. Sort the list using Bubble sort algorithm.
10. Write a Python program to read a few lines of text from the
keyboard and insert these lines into a file
fname=input("Enter the name of file to be created")
f=open(fname,"w")
print("Enter a few lines of text. Type 'end' to stop")
str=""
while True:
line=input()
if line=="end":
break
str+=line+"\n"
f.write(str)
f.close()
print("{} has been created".format(fname))
12. Write a Python program to copy the contents of file to another file
after converting the text to CAPITAL LETTERS.
fsource=input("Enter the name of source file")
fdest=input("Enter the name of destination file")
f1=open(fsource,"r")
f2=open(fdest,"w")
f2.write(f1.read().upper())
f1.close()
f2.close()
13. Write a Python program to delete those lines from a file that
contains a particular word
fname=input("Enter the file name : ")
with open(fname,"r") as f:
lines=f.readlines()
wname=input("Enter the word : ")
newlines=[]
for line in lines:
if wname not in line:
newlines.append(line)
with open(fname,"w") as f:
f.writelines(newlines)
16. Write a python program to read two numbers and display the
quotient. It should handle division by zero, invalid input exceptions
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
quotient = num1 / num2
print("The quotient is: {}".format(quotient))
except ValueError:
print("Invalid input. Please enter valid numbers.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
17. Write a Python program that reads a number from the user,
calculates its square root, and raises a custom (user defined)
exception if the number is negative:
import math
class NegativeNumberError(Exception):
def __init__(self, message=""):
self.message = message
super().__init__(self.message)
try:
num = float(input("Enter a number to calculate its square root:
"))
if num < 0:
raise NegativeNumberError("You entered a negative number.")
sqrt_value = math.sqrt(num)
print(f"The square root of {num} is: {sqrt_value}")
except NegativeNumberError as e:
print(f"Error: {e}")
18. write a python program to read an age in the range 1 to 100, and
classify as child, adolescent, adult, senior citizen etc. If the
age is out of range, raise an assertion error.
try:
age = int(input("Enter an age (1 to 100): "))
assert 1 <= age <= 100, "Age must be between 1 and 100."
except AssertionError as e:
print(f"Error: {e}")
import mysql.connector
try:
connection = mysql.connector.connect(
host="localhost",user="root",password="",database="c5data")
cursor = connection.cursor()
cursor.execute("""CREATE TABLE student(
roll_no INT,
name VARCHAR(50),
age INT,
place VARCHAR(50));""")
print("Table 'student' created successfully.")
cursor.execute("INSERT INTO student VALUES(1, "Arun", 20,
"Thiruvananthapuram");")
cursor.execute("INSERT INTO student VALUES(2, "Neethu", 22,
"Kochi");")
cursor.execute("INSERT INTO student VALUES(3, "Manu", 19,
"Kozhikode");")
cursor.execute("INSERT INTO student VALUES(4, "Anjali", 21,
"Thrissur");")
cursor.execute("INSERT INTO student VALUES(5, "Ravi", 23,
"Kollam");")
print("5 Records inserted successfully.")
connection.commit()
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
cursor.close()
connection.close()
print("MySQL connection closed.")
20. Write a Python Program to read data from the student table and
display the data on the screen.
import mysql.connector
try:
connection = mysql.connector.connect(
host="localhost",user="root",password="",database="c5data")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student;")
rows = cursor.fetchall()
for row in rows:
roll_no, fname, age, place = row
print(f"{roll_no}{name}{age}{place}")
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
cursor.close()
connection.close()
print("MySQL connection closed.")
**********