0% found this document useful (0 votes)
3 views

C5 python programs final

The document contains a series of Python programming exercises covering various topics such as number manipulation, string processing, file handling, exception handling, and database operations. Each exercise includes a brief description and the corresponding Python code to accomplish the task. The exercises range from basic tasks like displaying numbers in words to more complex tasks involving database interactions.

Uploaded by

firoshkhan4126
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C5 python programs final

The document contains a series of Python programming exercises covering various topics such as number manipulation, string processing, file handling, exception handling, and database operations. Each exercise includes a brief description and the corresponding Python code to accomplish the task. The exercises range from basic tasks like displaying numbers in words to more complex tasks involving database interactions.

Uploaded by

firoshkhan4126
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1.

Write a Python program to read a multi-digit number and display it


in words. For example, for the input 6281, output should be “Six
Two Eight One”.

n=input("Enter a multidigit number")


words=("Zero ","One ","Two ","Three ","Four ","Five ","Six ","Seven
","Eight ","Nine ")
for x in n:
print(words[int(x)],end="")

​ ​ ​ ​ ​ 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=" ")

2. Write a Python program to read a number and determine whether it is


Armstrong number or not. For example 153, 370, 371, 407, 1634,
8208, 9474 are armstrong numbers.

str=input("Enter a multidigit number")


num_digits=len(str)
s=0
for x in str:
s+=int(x)**num_digits
if s==int(str):
print("Amstrong")
else:
print("Not amstrong")

3. Write a Python program to read a sentence. Display the number of


vowels,consonents,digits and special characters in it.

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

print("Number of vowels={} , Cosonents={} , digis={} , special


characters={}".format(vcnt,ccnt,dcnt,scnt))

4. Read a sentence and a word. Determine whether the word is present in


the sentence or not

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")

5. Read a list of numbers. Display the list in ascending order and


descending order.

nums=[int(x) for x in (input("Enter a few numbers").split())]​


nums.sort()​
print("Ascending order:",nums)​
nums.sort(reverse=True)​
print("Descending order:",nums)

6. Read a list of numbers. Sort the list using Bubble sort algorithm.

x=[int(a) for a in (input("Enter a few numbers").split())]​


print("Given list : ",x)​
n=len(x)​
for i in range(n-1):​
for j in range(n-1-i):​
if(x[j]>x[j+1]):​
x[j],x[j+1]=x[j+1],x[j]​
print("Sorted list : ",x)

7. Write Python Program for Linear Search

str=(input("Enter a list of numbers")).split()


x=list(map(int,str))
value=int(input("Enter a value to search : "))
n=len(x)
for i in range(n):
if(x[i]==value):
print("Found at position",i+1)
break
else:
print("Not found")

8. Write a Python Program to count the number of words in a sentence

sentence = input("Enter a sentence: ")​


words = sentence.split()​
counts = {}​
for word in words:​
if word in counts.keys():​
counts[word] += 1​
else:​
counts[word] = 1​
for word, count in counts.items():​
print("{}={} times".format(word,count))​

9. Write a Python program to read a number and determine whether it is


Prime number or not.
n=int(input("Enter a number"))
for i in range(2,n//2+1):
if n%i==0:
print("Not a Prime Number")
break
else:
print("Prime Number")

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))

11. Write a Python program to display the contents of a text file on


the Screen.
fname=input("Enter the name of file to be displayed")
f=open(fname,"r")
print(f.read())
f.close()

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)

14. Write a Python program to reverse print a file.(last line first)

fname=input("Enter the file name : ")


with open(fname,"r") as f:
lines=f.readlines()
lines.reverse()
for line in lines:
print(line,end="")

15. Write a Python program to create an object of student class and


display its fields
class Student:
def __init__(self, name, age, mark):
self.name = name
self.age = age
self.mark = mark
def show(self):
print("Name: {}".format(self.name))
print("Age: {}".format(self.age))
print("Mark: {}".format(self.mark))
student1 = Student("Biju", 20, 85.5)
student1.show()

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."

if age <= 12:


classification = "Child"
elif 13 <= age <= 19:
classification = "Adolescent"
elif 20 <= age <= 59:
classification = "Adult"
else:
classification = "Senior"

print(f"The age {age} is classified as: {classification}")

except AssertionError as e:
print(f"Error: {e}")

19. write a python program to create a student table in the database


"c5data". The table should have fields roll_no, name,age and place.
Insert 5 records into the table.

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.")

**********

You might also like