0% found this document useful (0 votes)
25 views30 pages

Dse Assignment

This is from jaid hussain and marketing for beginners for vac exam today mt exam

Uploaded by

jaidh5194
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views30 pages

Dse Assignment

This is from jaid hussain and marketing for beginners for vac exam today mt exam

Uploaded by

jaidh5194
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

DSE

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

with open(file2, 'r') as fh:


names.extend(fh.readlines())

with open(output_file, 'w') as fh :


fh.writelines(names) # write all lines in output file
print("File is created with the of 'Question_9_output'.")

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

# form inputs label


name_label=Label(wind,text="Name :").grid(row=1,column=1)
email_label=Label(wind,text="Email :").grid(row=2,column=1)
phone_label=Label(wind,text="Phone No
:").grid(row=3,column=1)
# form inputs
entry_name=Entry(wind)
entry_name.grid(row=1,column=2,padx=10,pady=5)
entry_email=Entry(wind)
entry_email.grid(row=2,column=2,padx=10,pady=5)
entry_phone=Entry(wind)
entry_phone.grid(row=3,column=2,padx=10,pady=5)

# Submit form button


Button(wind,text="Register",
command=submit_form).grid(row=4,column=1,padx=10,pady=5
)
wind.mainloop()
if __name__=="__main__":
main()

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

# Calculate the age


age = today.year - birth_date.year - ((today.month,
today.day) < (birth_date.month, birth_date.day))

# Display the age


result_label.config(text=f"Your age is: {age} years")
except ValueError:
result_label.config(text="Invalid date entered. Please try
again.")
def main():
global date_entry, month_entry, year_entry, result_label
wind = Tk()
wind.title('Age Calculator')
wind.geometry('500x400')

Label(wind, text="Enter Date:").grid(row=0, column=0,


padx=10, pady=5)
Label(wind, text="Enter Month:").grid(row=1, column=0,
padx=10, pady=5)
Label(wind, text="Enter Year:").grid(row=2, column=0,
padx=10, pady=5)

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)

result_label = Label(wind, text="")


result_label.grid(row=4, 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()

# Write the details to a CSV file


with open('student_details_16.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([roll_no, enrollment_no, name, course,
semester])
# Clear the entries after submission
roll_no_entry.delete(0, END)
enrollment_no_entry.delete(0, END)
name_entry.delete(0, END)
course_entry.delete(0, END)
semester_entry.delete(0, END)

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

Label(wind, text="Roll No:").grid(row=0, column=0, padx=10,


pady=5)
Label(wind, text="Enrollment No:").grid(row=1, column=0,
padx=10, pady=5)
Label(wind, text="Name:").grid(row=2, column=0, padx=10,
pady=5)
Label(wind, text="Course:").grid(row=3, column=0, padx=10,
pady=5)
Label(wind, text="Semester:").grid(row=4, column=0,
padx=10, pady=5)

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)

confirmation_label = Label(wind, text="")


confirmation_label.grid(row=6, columnspan=2, pady=10)

wind.mainloop()

if __name__ == "__main__":
main()

#OUTPUT:-

You might also like