Complete Report File
Complete Report File
2 .FUNCTIONS 15-32
2.1Menu driven programme for even number odd number and number with series
2.3Write a programme using functions to calculate simple interest compound interest and emi for a plan
2.4Calculate area of different shapes circle I square a rectangle a parallelogram and trapezium
2.5Python programme to count following forgiveness number of alphabets number of words number of
vowels frequency of characters
3.1.4Write a python programme with function to read the text file data.txt and display those words
which have less than four characters
3.3.1Write user defined function to perform read and write operations on to a “student.csv” file
having fields roll number name stream and marks
4.1Write menu based programme to add delete and display the record of hostel using list as stack
Menu driven programme to demonstrate four major operations performed on a table through my
sql python connectivity
REVIEW OF
PYTHON
BASICS
# Program to check if a number is
prime or not
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
output
# Python program to check if the
number is an Armstrong number or not
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
output
#PYTHON PROGRAM TO CHECK IF
NUMBER IS PALINDROME OR NOT
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!”)
output
# PYTHON PROGRAM FOR FIBBONACCI
SERIES
n = int(input("Enter the number of terms for the
Fibonacci series: "))
a, b = 0, 1
if n <= 0:
print("Please enter a positive integer.")
elif n == 1:
print("Fibonacci series up to", n, "terms:")
print(a)
else:
print("Fibonacci series up to", n, "terms:")
print(a, b, end=" ")
for _ in range(2, n):
next_term = a + b
print(next_term, end=" ")
a, b = b, next_term
output
#PYTHON PROGRAM FOR
TRIBBONACCI SERIES
n = int(input("Enter the number of terms for the Tribonacci
series: "))
if n <= 0:
print("Please enter a positive integer.")
elif n == 1:
print("Tribonacci series up to", n, "term:")
print(0)
elif n == 2:
print("Tribonacci series up to", n, "terms:")
print(0, 0)
else:
tribonacci_series = [0, 0, 1]
if n >= 3:
print("Tribonacci series up to", n, "terms:")
print(0, 0, 1, end=" ")
for _ in range(3, n):
next_term = tribonacci_series[-1] + tribonacci_series[-
2] + tribonacci_series[-3]
tribonacci_series.append(next_term)
print(next_term, end=" ")
output
# python program for binary to decimal
conversion
binary_number = input("Enter a binary number: ")
output
# PYTHON PROGRAM FOR DECIMAL TO
OCTAL CONVERSION
decimal = int(input("Enter a decimal number: "))
# Initialize variables
octal = ""
# Handle the special case of 0
if decimal == 0:
octal = "0"
else:
# Convert decimal to octal
while decimal > 0:
remainder = decimal % 8
octal = str(remainder) + octal
decimal = decimal // 8
print(f"The octal equivalent is: {octal}")
output
# PROGRAM FOR DICE
import random
while True:
input("Press Enter to roll the dice...")
result = random.randint(1, 6)
print(f"You rolled a {result}")
play_again = input("Do you want to roll again? (yes/no):
").lower()
if play_again != "yes":
break
output
#PYTHON PROGRAM FOR SERIES 1 TO
20
output
FUNCTIONS
# Menu driven programme for even
number odd number and number with
series
# Function to check if a number is even or odd
def is_even_or_odd(number):
if number % 2 == 0:
return "even"
else:
return "odd"
# Function to generate a series of numbers
def generate_series(start, end):
return list(range(start, end + 1))
while True:
print("Menu:")
print("1. Check if a number is even or odd")
print("2. Generate a series of numbers")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
number = int(input("Enter a number: "))
result = is_even_or_odd(number)
print(f"{number} is an {result} number.")
elif choice == '2':
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
series = generate_series(start, end)
print("Series of numbers:", series)
elif choice == '3':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3).")
output
#Menu driven programme to convert
case of given text as users choice
# Function to convert text to sentence case
def to_sentence_case(text):
return text.capitalize()
while True:
print("Menu:")
print("1. Convert text to Sentence Case")
print("2. Convert text to lowercase")
print("3. Convert text to UPPERCASE")
print("4. Convert text to Title Case")
print("5. Exit")
if choice == '1':
text = input("Enter text to convert to Sentence Case: ")
result = to_sentence_case(text)
print("Converted text:", result)
elif choice == '2':
text = input("Enter text to convert to lowercase: ")
result = to_lower_case(text)
print("Converted text:", result)
elif choice == '3':
text = input("Enter text to convert to UPPERCASE: ")
result = to_upper_case(text)
print("Converted text:", result)
elif choice == '4':
text = input("Enter text to convert to Title Case: ")
result = to_title_case(text)
print("Converted text:", result)
elif choice == '5':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option
(1/2/3/4/5).")
output
#Write a programme using functions to
calculate simple interest compound
interest and emi for a plan
# Function to calculate Simple Interest (SI)
def simple_interest(principal, rate, time):
si = (principal * rate * time) / 100
return si
print("\nResults:")
print(f"Simple Interest (SI): {si:.2f}")
print(f"Compound Interest (CI): {ci:.2f}")
print(f"Monthly Installment (MI): {mi:.2f}")
output
# Calculate area of different shapes
circle I square a rectangle a
parallelogram and trapezium
import math
while True:
print("Menu:")
print("1. Calculate the area of a circle")
print("2. Calculate the area of a square")
print("3. Calculate the area of a rectangle")
print("4. Calculate the area of a parallelogram")
print("5. Calculate the area of a trapezium")
print("6. Exit")
if choice == '1':
radius = float(input("Enter the radius of the circle: "))
area = calculate_circle_area(radius)
print(f"The area of the circle is {area:.2f} square units.")
elif choice == '2':
side_length = float(input("Enter the side length of the
square: "))
area = calculate_square_area(side_length)
print(f"The area of the square is {area:.2f} square units.")
elif choice == '3':
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = calculate_rectangle_area(length, width)
print(f"The area of the rectangle is {area:.2f} square
units.")
elif choice == '4':
base = float(input("Enter the base of the parallelogram:
"))
height = float(input("Enter the height of the
parallelogram: "))
area = calculate_parallelogram_area(base, height)
print(f"The area of the parallelogram is {area:.2f} square
units.")
elif choice == '5':
base1 = float(input("Enter the first base of the
trapezium: "))
base2 = float(input("Enter the second base of the
trapezium: "))
height = float(input("Enter the height of the trapezium:
"))
area = calculate_trapezium_area(base1, base2, height)
print(f"The area of the trapezium is {area:.2f} square
units.")
elif choice == '6':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option
(1/2/3/4/5/6).")
output
#Python programme to count following
forgiveness number of alphabets
number of words number of vowels
frequency of characters
# Function to count the number of alphabets
def count_alphabets(text):
return sum(1 for char in text if char.isalpha())
while True:
print("Menu:")
print("1. Count the number of alphabets")
print("2. Count the number of words")
print("3. Count the number of vowels")
print("4. Calculate the frequency of characters")
print("5. Exit")
if choice == '1':
count = count_alphabets(text)
print(f"Number of alphabets: {count}")
elif choice == '2':
count = count_words(text)
print(f"Number of words: {count}")
elif choice == '3':
count = count_vowels(text)
print(f"Number of vowels: {count}")
elif choice == '4':
frequency = character_frequency(text)
print("Frequency of characters:")
for char, count in frequency.items():
print(f"{char}: {count} times")
elif choice == '5':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option
(1/2/3/4/5).")
OUTPUT
File handling
TEXT FILE
#Write a programme to read data from
text file and display number of Vowels
and constant
def count_vowels_and_consonants(filename):
try:
with open(filename, 'r') as file:
text = file.read()
vowels = "AEIOUaeiou"
vowel_count = 0
consonant_count = 0
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("An error occurred:", str(e))
# Example usage:
# Replace 'your_text_file.txt' with the name of your text file.
count_vowels_and_consonants('para.txt')
output
# Write a programme to read data from
a text file at display word which have
max and min connectors
def find_max_min_word(filename):
try:
with open(filename, 'r') as file:
text = file.read()
words = text.split()
if not words:
print("The file is empty.")
return
max_word = min_word = words[0]
for word in words:
if len(word) > len(max_word):
max_word = word
if len(word) < len(min_word):
min_word = word
print(f"Word with the maximum characters: {max_word}")
print(f"Word with the minimum characters: {min_word}")
except FileNotFoundError:
print("File not found.")
except Exception as e: print("An error occurred:", str(e)
find_max_min_word('your_text_file.txt')
output
#Write a python programme with
function to filtre (old file ,new file) that
copies all the lines of a text file
"source.txt" onto "target.txt" except
those lines which start with "@" sign
def filter_and_copy_lines(source_file, target_file):
try:
with open(source_file, 'r') as source, open(target_file,
'w') as target:
for line in source:
if not line.startswith('@'):
target.write(line)
print("Filtered and copied successfully.")
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("An error occurred:", str(e))
filter_and_copy_lines('source.txt', 'target.txt')
output
#Write a python programme
with function to read the text
file data.txt and display those
words which have less than
four characters
def display_short_words(filename):
try:
with open(filename, 'r') as file:
text = file.read()
words = text.split()
short_words = [word for word in words if len(word) <4]
print("Words with less than four characters:")
for word in short_words:
print(word)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("An error occurred:", str(e))
display_short_words('para.txt')
output
BINARY FILE
import pickle
def addrec():
l=[]
f=open("data.dat","ab")
rn=int(input("enter room number"))
pr=int(input("enter the price of room"))
rt=input("enter the type of room")
l=[rn,pr,rt]
pickle.dump(l,f)
print("record added in the file")
f.close()
addrec()
def disp():
try:
f=open("data.dat","rb")
while true:
d=pickle.load(f)
print(d)
except:
f.close()
disp()
def specific_rec(rno):
try:
f1=open("data.dat","rb")
while true:
d=pickle.load(f1)
if rno==d[0]:
print(d)
except:
f1.close()
try:
file=open("data.dat","rb")
f=open("temp1.dat","wb")
while true:
d=pickle.load(file)
if roll==d[0]:
d[1]=int(input("enter modified price"))
d[2]=input("enter modified room type")
pickle.dump(d,f)
except:
print("record updated")
file.close()
f.close()
os.remove("data.dat")
os.rename("temp1.dat","data.dat")
mod()
import os
def delete():
roll=int(input("enter room no. whose record you want to
delete"))
try:
file=open("data.dat","rb")
f=open("temp1.dat","wb")
while true:
d=pickle.load(file)
if roll!=d[0]:
pickle.dump(d,f)
else:
found=1
except:
print("record deleted")
file.close()
f.close()
os.remove("data.dat")
os.rename("temp1.dat","data.dat")
delete()
output
CSV FILE
#Write user defined function to perform read and write
operations on to a “student.csv” file having fields roll number
name stream and marks
import csv
def read_student_data(file_name):
student_data = []
try:
with open(file_name, mode='r', newline='') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
student_data.append(row)
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return student_data
while True:
roll_number = input("Enter Roll Number (or type 'done'
to finish): ")
if roll_number.lower() == 'done':
break
name = input("Enter Name: ")
stream = input("Enter Stream: ")
marks = input("Enter Marks: ")
records.append({'roll_number': roll_number, 'name':
name, 'stream': stream, 'marks': marks})
while True:
print("\nCSV File Menu:")
print("1. Write a Single Record")
print("2. Write All Records")
print("3. Exit")
if choice == "1":
write_single_record()
else:
print("Invalid choice. Please select a valid option.")
output
Stack
#Write menu based programme to add
delete and display the record of hostel
using list as stack
def add_record(stack, record):
stack.append(record)
print("Record added successfully.")
def delete_record(stack):
if not stack:
print("The stack is empty. No records to delete.")
else:
removed_record = stack.pop()
print(f"Record removed: {removed_record}")
def display_records(stack):
if not stack:
print("The stack is empty. No records to display.")
else:
print("Records in the stack:")
for record in stack:
print(f"Hostel Number: {record[0]}, Total Students:
{record[1]}, Total Rooms: {record[2]}")
hostel_records = []
while True:
print("Menu:")
print("1. Add a record")
print("2. Delete the top record")
print("3. Display all records")
print("4. Exit")
if choice == '1':
hostel_number = input("Enter Hostel Number: ")
total_students = input("Enter Total Students: ")
total_rooms = input("Enter Total Rooms: ")
record = (hostel_number, total_students, total_rooms)
add_record(hostel_records, record)
elif choice == '2':
delete_record(hostel_records)
elif choice == '3':
display_records(hostel_records)
elif choice == '4':
print("Goodbye!")
break
print("Invalid choice. Please select a valid option
(1/2/3/4).")
output
SQL QUERIES
(1) Create table a school bus (rt no integer(20), area covered
varchar(), Capacity integer(20), Noofstudents Integer(), transporter
integer(), charges integer):
(2) Desc school bus;
(3) Insert into schoolbus
values(1,’vasantkunj’,100,120,10,’shivam travels’,100000);
(4) Select * from schoolbus;
(5) Select * from SchoolBus order by Rtno where Capacity >
Noofstudent;
(6) Select Area_cover from SchoolBus where Distance > 20 and
Charges < 80000 ;
(7) SELECT TRANSPORTER , SUM(NoOfStudents) FROM SCHOOLBUS
GROUP BY TRANSPORTER;
(8) Select rtno , area_covered , Charges / Noofstudent as Average
from SchoolBus ;
(9) Insert into SchoolBus values (11, "Motibagh", 35, 32, 10, "kisan
tours", 35000) ;
(10) Select sum(distance) from school bus where transporter= "Yadav
travels";
(11) Select min(no of students) from school bus;
(12) Select avg(charges) from school bus where transporter = "Anand
travels";
(13) Select distinct transporter from school bus;
(14)select * from schoolbus order by area_covered;
(15) update sschoolbus set distance=’30’ where
area_covered=’janakpuri’;
(16) delete from schoolbus where area_covered=’janakpuri’;
Rtno Area_Covered Capacity NoofStudents Distance Transporter Charges