Dse Assignment
Dse Assignment
ASSIGNMENT
NAME : - JAID HUSSAIN
ROLL NO. : - 23PCS5148
COURSE : - B.SC PSCS
# Question - 1
'''Write a Python program to calculate the factorial of a
number.'''
def calculate_factorial(num):
if num==0 or num==1:
return 1
else:
return num*calculate_factorial(num-1)
def main():
num=int(input("Enter number : "))
factorial=calculate_factorial(num)
print(f"Factorial of {num} is {factorial}")
if __name__=='__main__':
main()
#output:-
# Question - 2
''’Write a Python program to generate prime numbers between
1 to n, where n is provided as input by
the user.'''
def isPrime(num):
for i in range(2,int(num**0.5)+1):
if num%i == 0:
return False
return True
def main():
num=int(input("Enter a number : "))
print(f"Prime numbers between {1} to {num} are :")
for el in range(2,num+1):
if isPrime(el):
print(el,end=" ")
if __name__=='__main__':
main()
#output:-
# Question - 3
'''Write a Python program to find the sum and average of
numbers in a given list. '''
def main():
numbers=list(map(int,input("Enter numbers seprated by
space : ").split()))
sum_nums=sum(numbers)
average=sum_nums/len(numbers)
print(f"Sum of numbers is {sum_nums} and average of
numbers is {average}")
if __name__=="__main__":
main()
#OUTPUT :-
# Question - 4
'''Given two sets, set1 and set2, write a Python program to find
their union, intersection and difference.'''
def main():
set1={1,2,5,4,5,11}
set2={9,6,5,10,3,1}
union_set=set1 | set2 # union of set1 and set2
intersection_set=set1 & set2 # intersection of set1 and set2
print(f"Intersection of set1 and set2 is - {intersection_set}")
print(f"Union of set1 and set2 is - {union_set}")
if __name__=="__main__":
main()
#OUTPUT:-
# Question - 5
"""Given a list of numbers, write a Python program to count the
number of times an element occurs in a
list and create a dictionary with element:count as key:value
pairs"""
def main():
numbers=[1,4,3,2,4,2,3,4,6,9,0,2,1,4]
ncd = {} # num count dict
for el in numbers:
if el in ncd:
ncd[el]+=1
else:
ncd[el]=1
print(f"Dictionary of numbers count is : {ncd}")
if __name__=="__main__":
main()
#OUTPUT:-
# Question - 6
"""Write a Python program to swap the first two and last two
characters in a given string."""
def main():
mystr = input("Write word for string : ")
swapped_str=mystr[-1:-3:-1]+mystr[2:-2]+mystr[1::-1]
print(f"After swapping first two character of string with last
two , string converted to - {swapped_str}")
if __name__=="__main__":
main()
#OUTPUT:-
# Question - 7
"""Write a Python program to create a text file having names of
ten Indian cities."""
def main():
i_c_n= input("Enter ten indian cities name seprated by ',' :
").split(',') # indian cities names
if len(i_c_n) < 10:
print('Cities names are less than 10 ')
else:
fh=open("Question_7.txt",'w')
for city in i_c_n :
fh.write(city.strip()+'\n')
if __name__=="__main__":
main()
#OUTPUT:-
# Question - 8
"""Write a Python program to create a text file having five lines
about your college using Writelines() function """
def main():
lines=[]
for _ in range(5):
line=input("Write a line about your columnlege : ")
lines.append(line+" \n")
# create text file to write the lines about columnlege
with open('Question_8.txt','w') as fh:
fh.writelines(lines)
if __name__=="__main__":
main()
#OUTPUT:-
# Question - 9
'''Write a Python program which reads the data from two input
files having Employee Names and
merges them into one output file. '''
def main():
file1='Question_9_input1.txt' # input file 1 ( in both file
employee names are sprated by new line
file2='Question_9_input2.txt' # input file 2
output_file="Question_9_output.txt" # output file , will
contain employee name of both input files
names=[]
with open(file1, 'r') as fh:
names.extend(fh.readlines()) # fh.readlines() return list of
lines
names[len(names)-1]+="\n" # add new line char to last
element of list
if __name__=="__main__":
main()
#OUTPUT:-
# Question - 10
''' Write a Python program to count the number of vowels in a
file and write the vowel : count in a dictionary. '''
def main():
filename="Question_10.txt" # input file
MyDict={} # dictionary contains count of vowel
vowels=['a','i','o','u','e']
with open(filename, 'r') as fh :
content=fh.read().lower()
for el in vowels:
count=content.count(el) # count occurence of a vowel in
content
MyDict[el]=count # create dict element of that
vowel
print(MyDict)
if __name__=="__main__":
main()
#OUTPUT:-
#QUESTION:- 11
""" write a python programe to create a csv file having student
data: Roll no ,
Enrollment no, name , course, semester"""
import csv
filename="student_data2.csv"
header=["Roll no.","Enrollment
no.","Name","Course","Semester"]
n=int(input("Enter the no. of Data"))
with open(filename,mode="w",newline=" ") as file:
writer=csv.writer(file)
writer.writerow(header)
for i in range(n):
print("Enter the details of student")
Roll_no=int(input("Enter the Roll no."))
Enrollment_no=int(input("Enter the Enrollment no."))
Name=(input("Enter the Name of student"))
Course=input("Enter the Course")
Semester=int(input("Enter the semester"))
writer.writerow([Roll_no, Enrollment_no, Name, Course,
Semester])
print("written successful")
#OUTPUT:-
#QUESTION:-12
"""write a python program library to read the csv file created in
the above programe and
filter out record of II semester students."""
import csv
with open("student_data2.csv","r")as file1:
file_read=csv.reader(file1)
header=next(file_read)
sem_index=header.index("semester")
for row in file_read:
if row[sem_index]=="2":
filter_row=row
print(filter_row)
with open("II_sem.csv","w",newline="")as output_file:
to_write=csv.writer(output_file)
to_write.writerow(header)
to_write.writerow(filter_row)
print("successfully written in II sem student file")
#OUTPUT:-
#QUESTION:-13
'''Write a Python program using tkinter library to create a GUI to
enter registration details for an event.'''
from tkinter import *
# function to handle submit form action
def submit_form():
global entry_name, entry_email,entry_phone
name=entry_name.get()
email=entry_email.get()
phone=entry_phone.get()
print(f" Name - {name} \n Email - {email} \n Phone - {phone}")
def main():
global entry_name, entry_email,entry_phone
wind=Tk()
wind.geometry("500x500")
wind.title("Event Registration Form")
#OUTPUT:-
#QUESTION :-14
'''Write a Python program using tkinter library to create a
calculator to perform addition, subtraction, multiplication and
division of two numbers entered by the user.'''
from tkinter import *
import math
# function to handle click event
def click(event):
global scvalue,Screen
try:
text=event.widget.cget('text')
Screen.update()
if text=="=":
if scvalue.get().isdigit():
value=int(scvalue.get())
else :
value=eval(scvalue.get())
scvalue.set(value)
Screen.update()
elif text=="C":
scvalue.set("")
Screen.update()
else:
scvalue.set(scvalue.get()+text)
except SyntaxError:
scvalue.set('Error')
Screen.update()
print('Error')
def main():
window=Tk()
window.geometry('440x580')
window.config(bg='grey')
global Screen,scvalue
scvalue=StringVar()
Screen=Entry(window,textvariable=scvalue,font='comicsanms
40 bold')
Screen.pack(pady=10,padx=5)
f1=Frame(window,bg='white')
f1.pack(pady=5,side=BOTTOM)
f2=Frame(window,bg='white')
f2.pack(pady=5,side=BOTTOM)
f3=Frame(window,bg='white')
f3.pack(pady=5,side=BOTTOM)
f4=Frame(window,bg='white')
f4.pack(pady=5,side=BOTTOM)
list1=['0','1','2','3','4','5','6','7','8','9','+','-','*','/','%','=','C','**']
for i in list1:
if list1.index(i)<5:
b=Button(f4,text=i,bg='black',fg='white',font='lucida 37
bold')
b.pack(side=LEFT,padx=5,pady=5)
b.bind('<Button-1>',click)
elif list1.index(i)<10 and list1.index(i)>=5:
b=Button(f3,text=i,bg='black',fg='white',font='lucida 37
bold')
b.pack(side=LEFT,padx=5,pady=5)
b.bind('<Button-1>',click)
elif list1.index(i)>=10 and list1.index(i)<15:
b=Button(f2,text=i,bg='black',fg='white',font='lucida 37
bold')
b.pack(side=LEFT,padx=5,pady=5)
b.bind('<Button-1>',click)
elif list1.index(i)>=15 and list1.index(i)<20:
b=Button(f1,text=i,bg='black',fg='white',font='lucida 31
bold')
b.pack(side=LEFT,padx=2,pady=5)
b.bind('<Button-1>',click)
# display window
window.mainloop()
if __name__=="__main__":
main()
#OUTPUT:-
#QUESTION :- 15
'''Write a Python program using tkinter library to create an age
calculator to calculate age when DOB is entered'''
from tkinter import *
from datetime import datetime
def Age_Calculator():
# Get the entered date, month, and year
day = date_entry.get()
month = month_entry.get()
year = year_entry.get()
try:
# Convert the entered values to integers
birth_date = datetime(int(year), int(month), int(day))
today = datetime.now()
date_entry = Entry(wind)
date_entry.grid(row=0, column=1, padx=10, pady=5)
month_entry = Entry(wind)
month_entry.grid(row=1, column=1, padx=10, pady=5)
year_entry = Entry(wind)
year_entry.grid(row=2, column=1, padx=10, pady=5)
Button(wind, text='Submit',
command=Age_Calculator).grid(row=3, columnspan=2,
pady=10)
wind.mainloop()
if __name__ == "__main__":
main()
#OUTPUT:-
QUESTION :-16
'''Write a Python program using tkinter library to read student
details, namely, RollNo, Enrollment_No, Name, Course,
Semester, through a form and write the entered student details
to a CSV file.'''
import csv
from tkinter import *
def submit_details():
# Get the entered details
roll_no = roll_no_entry.get()
enrollment_no = enrollment_no_entry.get()
name = name_entry.get()
course = course_entry.get()
semester = semester_entry.get()
confirmation_label.config(text="Details submitted
successfully!")
def main():
global roll_no_entry, enrollment_no_entry, name_entry,
course_entry, semester_entry, confirmation_label
wind = Tk()
wind.title('Student Details')
wind.geometry('500x400')
roll_no_entry = Entry(wind)
roll_no_entry.grid(row=0, column=1, padx=10, pady=5)
enrollment_no_entry = Entry(wind)
enrollment_no_entry.grid(row=1, column=1, padx=10,
pady=5)
name_entry = Entry(wind)
name_entry.grid(row=2, column=1, padx=10, pady=5)
course_entry = Entry(wind)
course_entry.grid(row=3, column=1, padx=10, pady=5)
semester_entry = Entry(wind)
semester_entry.grid(row=4, column=1, padx=10, pady=5)
Button(wind, text='Submit',
command=submit_details).grid(row=5, columnspan=2,
pady=10)
wind.mainloop()
if __name__ == "__main__":
main()
#OUTPUT:-