Indira Gandhi Delhi Technical
University for Women
(established by the Govt. NCT of Delhi vide Delhi Act 09 of 2012)
(Formerly Indira Gandhi Institute of Technology)
Kashmiri Gate, Delhi – 110006
Submitted to:
Dr. Ankita Singh
IT Department
Submitted By:
Sapna Morya
MCA (Sem-1)
Programming with Python
ASSIGNMENT - 1
Ques1. WAP in python to print ‘hello World’.
Ans. Print(‘hello World’)
Ques2. List all the python IDEs and compare them.
1. Ans. PyCharm
o One of the most popular IDEs for Python, made by JetBrains.
o Full-featured: code completion, debugging, testing, database tools, version
control.
o Great for big projects, web development (Django/Flask).
o Free (Community) and Paid (Professional) versions.
2. VS Code (Visual Studio Code)
o Lightweight editor that becomes powerful with extensions.
o Supports Python (via extension), debugging, Git, Jupyter notebooks.
o Works for both small scripts and big projects.
o Free and widely used across all languages.
3. Jupyter Notebook / JupyterLab
o Browser-based notebook system.
o Ideal for data science, ML, and experimentation.
o Lets you run code in small cells with inline graphs and markdown notes.
o Not suitable for large applications.
4. Spyder
o Scientific IDE made for data science and numerical analysis.
o Looks like MATLAB, includes variable explorer and plotting tools.
o Used heavily in academic/scientific research.
5. IDLE
o Comes built-in with Python.
o Very basic, just for writing and running small scripts.
o Good for quick testing but not powerful.
6. PyDev (Eclipse plugin)
o Python support for Eclipse IDE.
o Useful if you already work in Eclipse with other languages.
o Full features but Eclipse is heavy.
Comparison Table of Python IDEs
IDE / Editor Best For Strengths Weaknesses Cost
PyCharm Large projects, Rich features, Heavy, Pro Free
web smart version is paid (Community) /
frameworks completion, great Paid (Pro)
debugging
VS Code General Lightweight, Needs Free
coding, multi- extensible, free extensions for
language full Python
power
Jupyter Data science, Interactive cells, Not for big apps, Free
Notebook/Lab ML, research inline graphs, messy code
markdown
Spyder Scientific MATLAB-like, Not great for Free
computing variable explorer, web dev
plotting
IDLE Quick scripts, Comes with Very limited Free
learning Python, no setup features
PyDev Eclipse users Full IDE inside Eclipse is bulky, Free
Eclipse setup heavy
Ques3. What are python libraries? Use any 5-6 libraries and describe their purpose.
Ans. A Python library is a collection of pre-written code (modules, classes, functions) that
you can import into your program so you don’t have to “reinvent the wheel.”
Instead of writing everything from scratch, you can just use these libraries to save time,
improve efficiency, and focus on solving your actual problem.
🔹 Examples of Popular Python Libraries & Their Purpose
1. NumPy
o Stands for Numerical Python.
o Provides support for large, multi-dimensional arrays and matrices.
o Includes lots of mathematical functions (linear algebra, statistics, random
numbers).
o Use case: Any scientific calculation, data manipulation, or ML preprocessing.
2. Pandas
o Built on top of NumPy.
o Used for data manipulation and analysis.
o Provides DataFrame and Series objects (like Excel tables).
o Use case: Cleaning datasets, handling CSV/Excel files, working with time
series data.
3. Matplotlib
o A data visualization library.
o Lets you create static, interactive, and animated plots (line, bar, histogram,
pie, scatter).
o Use case: Visualizing data trends and patterns.
4. Scikit-Learn
o A machine learning library built on top of NumPy, SciPy, and Matplotlib.
o Offers tools for classification, regression, clustering, model evaluation.
o Use case: Training ML models like decision trees, SVM, or regression.
5. TensorFlow / PyTorch
o Both are deep learning frameworks.
o TensorFlow (by Google) & PyTorch (by Meta) are used for building and
training neural networks.
o Use case: AI, natural language processing, computer vision, chatbots,
recommendation systems.
6. Requests
o A library to make HTTP requests (GET, POST, PUT, DELETE).
o Simplifies API communication and web scraping.
o Use case: Fetching data from the internet, calling REST APIs.
ASSIGNMENT - 2
Q2. WAP in python to add, subtract, multiply and divide two numbers
Ans. num1 = int(input('Enter a number'))
num2 = int(input('Enter another number'))
print('sum of two numbers is:',num1+num2)
print('substraction of two numbers is:',num1-num2)
print('multiplication of two numbers is:',num1*num2)
print('division of two numbers is:',num1/num2)
Q3. WAP in python to swap two numbers.
Ans. num1 = 5
num2 = 10
print("before swapping value of Num1 is",num1,"and Num2 is",num2)
temp=num1
num1=num2
num2=temp
print("after swapping value of Num1 is",num1,"and Num2 is",num2)
Q4. WAP in python to if number entered by user is even or odd.
Ans. num= int(input("Enter a number"))
if num%2==0:
print("Number is Even")
elif num%2==1:
print("Number is Odd")
else:
print("invalid input")
[Link] in python to identify data type of variables.
Ans. var1= "Python"
var2= 5
var3= 3.14
var4= True
var5= 'A'
print(type(var1))
print(type(var2))
print(type(var3))
print(type(var4))
[Link] in python to check prime number.
Ans. num= int(input('Enter a number'))
i=num/2
while (i>1):
if (num%i==0):
print("number is not prime")
break
else:
i=i-1
else:
print("number is prime")
Q7. WAP in python to check whether a number is palindrome or not.
Ans. num = int(input('Enter a number'))
reverse=0
temp = num
while temp>0:
reverse= (reverse*10)+(temp%10)
temp=temp//10
if reverse==num:
print('Number is palindrome')
else:
print('Number is not palindrome')
Q8. WAP in python to find factorial of a number.
Ans. num = int(input('Enter a number'))
fact = 1
for i in range (num,0,-1):
fact=fact*i
i=i-1
print('factorial of this numbers is :', fact)
Q9. WAP in python to print table of a number.
Ans. num = int(input('Enter a number'))
for i in range (1,11):
print(num,'*',i,'=',num*i)
Q10. WAP in python to check Armstrong number.
Ans. num = int(input('Enter a number'))
num_str = str(num)
length=len(num_str)
sum=0
for i in num_str:
j=int(i)
sum=sum +(j**length)
if sum==num:
print('Number is armstrong')
else: print('Number is not armstrong')
Q11. WAP in python to check leap year.
Ans. Year= int(input('Enter a Year'))
if (Year % 400 == 0):
print("It's a leap year")
elif (Year%100!=0 and Year%4==0):
print("It's a leap year")
else:
print("It's not a leap year")
Q12. WAP in python to check whether a triangle is valid or not.
Ans. a=int(input('Enter a side of a triangle'))
b=int(input('Enter another side of a triangle'))
c=int(input('Enter third side of a triangle'))
if (a+b>c and b+c>a and a+c>b):
print("It's a valid triangle")
else:
print("Triangle is not valid")
ASSIGNMENT - 3
Q13. WAP in python using range, break and continue.
Ans. for i in range(1,15):
if (i%2==0):
continue
elif (i==13):
break
else :
print(i)
Q14. WAP in python to show pattern using loop.
Ans.
(i) for i in range (1,10):
print("* "*i)
(ii) for i in range (1,10):
for j in range (1,i+1):
print(i,end="")
print(" ")
(iii) for i in range (10,1,-1):
for j in range (10,i-1,-1):
print(i,end="")
print( )
ASSIGNMENT - 4
Q15. WAP in python to create pattern.
Ans. n=5
for i in range (1,n+1):
print(" "*(n-i),"* "*i)
for i in range (n-1,0,-1):
print(" "*(n-i),"* "*i)
Q16. WAP in python to count number of odd and even numbers from a series of numbers.
Ans. numbers = (1,2,3,4,5,6,7,8,9)
even=0
odd=0
for i in numbers:
if (i%2==0):
even+=1
elif (i%2==1):
odd+=1
else:
continue
print("Totals even numbers are :",even)
print("Totals odd numbers are :",odd)
Q17. WAP in python that prints numbers from 0 to 6 except 3 and 6.
Ans. for i in range(0,7):
if i==3:
continue
elif i==6:
break
else:
print(i,end="")
Q18. WAP in python to print first 10 natural numbers using while loop.
Ans. i=1
while i<=10:
print(i)
i+=1
Q19. WAP in python to create the pattern.
Ans. for i in range(1,6):
for j in range(1,i+1):
print(j,end=" ")
print("")
Q20. WAP in python to display numbers from -10 to -1 using for loop.
Ans. for i in range(-10,0):
print(i)
ASSIGNMENT - 5
Q21. Write a Python function to find the maximum of three numbers.
Ans. def maximum_of_three(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
print("The maximum number is:", maximum_of_three(num1, num2, num3))
Q22. WAP to convert temperature from Celsius to Fahrenheit.
Ans. celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit}°F")
Q23. WAP to find sum of even numbers upto n.
Ans. n = int(input("Enter a number: "))
sum_even = 0
for i in range(2, n+1, 2):
sum_even += i
print("Sum of even numbers up to", n, "is:", sum_even)
Q24. WAP to calculate are of circle.
Ans. r= int(input("enter radius"))
area= 2*3.147*r
print("Area of this circle is :", area)
Q25. WAP to show use of variable length of arguments in functions,default and keyword
arguments and use of inner and anonymous functions.
Ans. def greet(name, msg="Welcome!", emoji="😊"):
print(f"Hello {name}, {msg} {emoji}")
def show_details(*args, **kwargs):
print("Args:", args) # tuple
print("Kwargs:", kwargs) # dictionary
def outer_function(x):
def inner_function(y): # inner function
return y * y
return inner_function(x) # calling inner function inside outer
square = lambda n: n * n
greet("Rahul") # uses default msg & emoji
greet("Vikram", emoji="🔥") # keyword arg
print()
show_details(10, 20, 30, name="Alice", age=21)
print()
print("Square using inner function:", outer_function(5))
print("Square using lambda:", square(6))
ASSIGNMENT - 6
Q26. Write a Python program to create a list of 10 numbers and print the first, last, and
middle element of the list.
Ans. L1 = [1,2,3,4,5,6,7,8,9,10]
print("First element is: ", L1[0])
print("Middle element is: ", L1[9])
print("Last element is: ", L1[4])
Q27. Write a program to find the sum and average of elements in a list.
Ans. List1= [5,10,15,20,25]
Total= sum(List1)
Length= len(List1)
Avg= Total/Length
print("Sum of all elements is :", Total)
print("Average of all elements is :", Avg)
Q28. Given a list of numbers, write a program to find the maximum and minimum number.
Ans. List1= [5,10,153,200,25]
print("Maximum value is:", max(List1))
print("Minimum value is :", min(List1))
Q29. WAP in python to reverse a list without using the built-in reverse() function.
Ans. List1= [5,10,153,200,25]
print("Original list is :", List1)
print("Reversed list is :", List1[::-1])
Q30. Write a program to count the occurrences of a specific element in a list.
Ans. List1= [5,10,153,200,25,10,20,2,15,55,20,10,11,10]
value= int(input("Enter a value"))
count=0
for i in List1:
if (i==value):
count+=1
print("Count of",value,"in list is :",count)
ASSIGNMENT – 7
Q31. a) Create a tuple and access elements using indexing and slicing.
Ans. tup1= (5,10,153,200,25,10,20,21,15,55,20,100,11,150)
print("Tuple is : ",tup1)
print("First Element is :",tup1[0])
print("Last Element is :",tup1[13])
print("First five elements of tuple is :",tup1[0:5])
b) Find the length of a tuple, concatenate two tuples.
Ans. tup1= (5,10,153,200,25,10,20)
length=len(tup1)
print("Length of the Tuple is : ",length)
print("New tuple is :",tup1+tup2)
Q32. Create a set and perform add (), remove (), and discard (). Find union, intersection,
difference, and symmetric difference of two sets.
Ans. set1= {5,10,15,20}
set2= {2,4,6,8}
print("Set is : ",set1)
[Link](25)
print("Set after adding an element:",set1)
[Link](10)
print("Set after removing an element:",set1)
[Link](12)
print("Set after discarding an element:",set1)
print("Set 2 is : ",set2)
uinion_set= [Link](set2)
print("Union set :",uinion_set)
intersection_set= [Link](set2)
print("Intersection set :",intersection_set)
diff_set= [Link](set2)
print("Difference set :",diff_set)
sym_dif= set1.symmetric_difference(set2)
print("Symmetric Difference set :",sym_dif)
Q33. Create a dictionary and access values using keys. Add, update, and delete dictionary
elements. Iterate through keys, values, and key-value pairs.
Ans. price = {"Apple": 120,"Banana": 40,"Mango": 150,"Orange": 80,"Grapes": 90}
print("Price of Apple is :",price["Apple"])
price["Watermelon"] = 100
print("After adding Element :",price)
price["Mango"]=160
print("After updating Element :",price)
[Link]("Banana")
print("After removing Element :",price)
print("Keys: ",end=" ")
for key in price:
print(key,end=" ")
print()
print("Values: ",end=" ")
for value in [Link]():
print(value,end=" ")
print()
print("Key-Value pairs",end=" ")
for key, value in [Link]():
print(key, ":", value,end=" ")
ASSIGNMENT – 8
Q34. WAP to swap two numbers using tuple assignment.
Ans. x= 10;
y= 20;
print("Value of x:",x)
print("Value of x:",y)
x,y=y,x
print("New value of x:",x)
print("New value of y:",y)
Q35. WAP that has a nested list to store details of toppers details. Edit the details and print.
Ans. L_stu =[["Alice", "10A", 98],["Bob", "10B", 95],["Charlie", "10A", 99]]
print("Old List: ",L_stu)
L_stu[1]=["Berlin", "10C", 84]
print("New List: ",L_stu)
Q36. WAP that generate a set of even numbers and another set of odd numbers.
Demonstrate result of union, intersection, difference.
Ans. set1={1,3,5,7,9}
set2={2,4,6,8}
print("Union of set1 and set2 is : ",[Link](set2))
print("Intersection of set1 and set2 is : ",[Link](set2))
print("Difference of set1 and set2 is : ",[Link](set2))
Q37. WAP that creates a dictionary of radius of circle and it's circumference.
Ans. radii=[1,2,3,4,5]
circle_dict={}
for i in radii:
circle_dict[i]=round(2*3.147*i,3)
print("Dictionary is : ",circle_dict)
[Link] to sort (ascending and descending) a dictionary by value.
Ans. my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 3}
sorted_asc = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print("Dictionary in ascending values:", sorted_asc)
sorted_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print("Dictionary in descending values:", sorted_desc)
ASSIGNMENT – 9
Q39. WAP that reads text from a file and writes into another file.
Ans. f1=open("my_file.txt","r")
f2=open("[Link]","r+")
data=[Link]()
print("file before writing :",[Link]())
[Link](data)
[Link]()
f2=open("[Link]","r")
print("file after writing :",[Link]())
Q40. WAP that reads a file and print only those lines that has the word python.
Ans. f1=open("my_file.txt","r")
for line in [Link]():
if ("Python" in line):
print(line)
[Link]()
Q41. WAP to compare two files.
Ans. f1=open("my_file.txt","r")
f2=open("[Link]","r")
data1=[Link]()
data2=[Link]()
if (data1==data2):
print("files are identical")
[Link]()
[Link]()
Q42. WAP that accept a file name and a character as input from the user and count no. of
times a character apperar in a file.
Ans. f1=open("my_file.txt","r")
ch=input("Enter character to find : ")
count=0
for i in [Link]():
if(i==ch):
count+=1
print("Count of",ch,"in file is: ",count)
[Link]()
Q43. WAP to perform linear search and binary search.
Ans. Linear Search :
l1=[1,5,9,2,6,8,4,7,0]
ch=int(input("Enter value to search"))
flag=0
for i in l1:
if i==ch:
print(ch,"is in the list")
flag=1
if(flag==0):
print(ch," not found in list")
Binary Search :
L1=[10,20,30,40,45,50,56,70]
ch=int(input("Enter a number : "))
flag=0
low = 0
high = len(L1) - 1
while low <= high:
mid = (low + high) // 2
if L1[mid] == ch:
print(ch,"found at index",mid)
flag=1
break
elif L1[mid] < ch:
low = mid + 1
else:
high = mid - 1
if flag==0:
print(ch," not found")
Q44. WAP to perform sorting in a list using sort and sorted.
Ans. L1=[100,20,10,84,45,90,56,70]
L2=sorted(L1)
print("Original List : ",L1)
[Link]()
print("List with sorted function : ",L2)
print("List with sort function : ",L1)
ASSIGNMENT – 10
Q45. WAP to read from a file([Link]) and display on console.
Ans. with open("[Link]", "r") as file:
content = [Link]()
print("File Content:", content)
Q46. WAP to take Command line Input from the user.
Ans. import sys
name = [Link][1]
print("Hello,", name)
Q47. WAP to show the use os and sys module.
Ans. import os
import sys
print("Python Version (using sys):", [Link])
print("Command line arguments (using sys):", [Link])
print("Current Working Directory (using os):", [Link]())
print("List of files in current directory (using os):", [Link]())
ASSIGNMENT – 11
Q48. WAP to handle division by zero using try-except.
Ans. try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result =", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
Q49. WAP that handles both ValueError and ZeroDivisionError(multiple exception).
Ans. try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result =", result)
except ValueError:
print("Error: Please enter valid integers only!")
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")
Q50. WAP demonstrate the use of else and finally with exceptions.
Ans. try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
except ZeroDivisionError:
print("Error: Denominator cannot be zero.")
else:
print("Division successful. Result =", result)
finally:
print("Execution completed. (This block always runs)")
Q51. WAP to Handle file read/write exceptions.(FileNotFoundError).
Ans. try:
filename = input("Enter filename to read: ")
with open(filename, 'r') as f:
data = [Link]()
print("File content:\n", data)
except FileNotFoundError:
print("Error: The file does not exist. Please check the filename.")
Q52. Demonstrate nested exception handling.
Ans. try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
try:
result = a / b
print("Result =", result)
except ZeroDivisionError:
print("Inner Exception: Division by zero.")
except ValueError:
print("Outer Exception: Invalid input. Please enter numbers only.")
finally:
print("Program execution finished.")
MID SEM EXAMINATION
Q1.
(a) 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")
(b)
i) Random access in a file:
Random access means reading or writing at any position in a file without reading
sequentially.
f = open("[Link]", "r+")
[Link](10) # move file pointer to 10th byte
data = [Link](5)
ii) Command line input:
Input provided through terminal when running a program.
Example:import sys
name = [Link][1]
print("Hello", name)
(c) marks = {'Anjali': [80, 75, 60], 'Sooraj': [45, 75, 50], 'Disha': [70, 90, 55]}
def analyze_marks(marks):
avg_marks = {name: sum(m)/len(m) for name, m in [Link]()}
max_avg = max(avg_marks.values())
toppers = [n for n, a in avg_marks.items() if a == max_avg]
failed = [n for n, m in [Link]() if any(x < 35 for x in m)]
return toppers, failed
print("Highest average:", analyze_marks(marks)[0])
print("Failed students:", analyze_marks(marks)[1])
Q2. (a)
(i)Output:
Explanation:
continue skips the rest of the current loop iteration.
When count == 3, print(count) is skipped.
The loop ends when count reaches 5.
If we replace continue with:
break → exits the loop immediately when count == 3.
Output:
1
2
pass → does nothing (acts as a placeholder).
Output:
1
2
3
4
5
(ii) range() is used to generate a sequence of numbers, often used with loops.
Example:
for i in range(1, 6):
print(i)
range(start, stop, step) → generates values from start to stop-1.
Used to control iteration count in for loops.
(b)(i)
i Condition Calculation Updated
result
1 even result = 0 + 14×2 28
4
0 even result = 28 + 0×2 28
1 odd result = 28 - (13//2)=28-6 22
3
5 odd result = 22 - (5//2)=22-2 20
7 odd result = 20 - (7//2)=20-3 17
Output:
Result: 17
Explanation:
For even numbers → multiply by 2 and add.
For odd numbers → perform integer division by 2 and subtract
(ii) n = int(input("Enter a number: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print("Factorial of", n, "is", fact)
(c)(i)
if-else statement is the most basic decision-making structure in Python. It checks a
condition, and if it evaluates to True, one block of code executes; otherwise, the else block
runs. It is best suited for simple two-way decisions — for example, checking whether a
number is even or odd.
Nested if statement means placing one if statement inside another. It is used when one
condition depends on the truth of another. For instance, checking if a number is positive and
then further checking if it is even or odd. However, nested if statements can make the code
longer and harder to read if overused.
Match statement was introduced in Python 3.10 as a more readable alternative to multiple
if-elif-else chains. It works like a switch-case statement found in other programming
languages. The variable being tested is compared against several constant patterns, and the
block matching the pattern is executed.
(ii) length = float(input("Enter length: "))
breadth = float(input("Enter breadth: ")
area = length * breadth
perimeter = 2 * (length + breadth)
print("Area =", area)
print("Perimeter =", perimeter)
if area > perimeter:
print("Area is greater than perimeter.")
elif area == perimeter:
print("Area is equal to perimeter.")
else:
print("Perimeter is greater than area.")
Q3. (a)
(i) Using slicing
s = "Python"
rev = s[::-1]
print("Reversed string:", rev)
Without slicing
s = "Python"
rev = ""
for ch in s:
rev = ch + rev
print("Reversed string:", rev)
(ii) x = 10 # global
def outer():
y = 20 # enclosed
def inner():
z = 30 # local
print(x, y, z)
inner()
outer()
(b) nums = [10, 45, 23, 90, 67]
largest = second = float('-inf'
for n in nums:
if n > largest:
second = largest
largest = n
elif n > second and n != largest:
second = n
print("Second largest element is:", second)
(c) dict1 = {'a': 10, 'b': 20, 'c': 30}
dict2 = {'b': 15, 'c': 5, 'd': 40}
print("Traversing dict1:")
for key, value in [Link]():
print(key, ":", value)
merged = [Link]()
for k, v in [Link]():
merged[k] = [Link](k, 0) + v
print("Merged Dictionary:", merged)
ASSIGNMENT – 12
Q53. Create a program to store employee details (name, department, salary) in a dictionary.
Save and retrieve this data from a file, handling any possible exceptions.
[Link] main():
employees = {}
try:
file = open("[Link]", "r")
for line in file:
data = [Link]().split(",")
if len(data) == 3:
name, dept, salary = data
employees[name] = {"Department": dept, "Salary": salary}
[Link]()
except FileNotFoundError:
pass
except Exception as e:
print("Error reading file:", e)
while True:
name = input("Enter employee name: ")
dept = input("Enter department: ")
salary = input("Enter salary: ")
employees[name] = {"Department": dept, "Salary": salary}
try:
file = open("[Link]", "w")
for n, details in [Link]():
[Link](n + "," + details["Department"] + "," + details["Salary"] + "\n")
[Link]()
except Exception as e:
print("Error writing to file:", e)
ch = input("Do you want to add another employee? (y/n): ")
if [Link]() != "y":
break
print("\nStored Employee Data:")
for n, details in [Link]():
print("Name:", n, "Department:", details["Department"], "Salary:", details["Salary"])
main()
Q54. Store students and their marks in a dictionary, calculate average, and handle invalid
inputs.(Concepts Used:Dictionary storing list and calculated values, Exception handling for
invalid input and division errors(Division and value error)).
Ans. students = {}
while True:
try:
name = input("Enter student name: ")
marks_input = input("Enter marks separated by spaces: ")
marks = []
for m in marks_input.split():
[Link](int(m)) # may raise ValueError
avg = sum(marks) / len(marks)
students[name] = {"Marks": marks, "Average": avg}
except ValueError:
print("Invalid mark entered. Please enter numbers only.")
continue
except ZeroDivisionError:
print("No marks entered. Cannot calculate average.")
continue
choice = input("Add another student? (y/n): ")
if [Link]() != "y":
break
print("\nStudent Records:")
for name, details in [Link]():
print("Name:", name, "Marks:", details["Marks"], "Average:", details["Average"])
Q55. Write a program that randomly generates a number and raise a user defined exception
if number is below 1.
Ans. import random
class NumberTooSmallError(Exception):
try:
num = [Link](-5, 5) # randomly generate a number
print("Generated Number:", num)
if num < 1:
raise NumberTooSmallError("Number is below 1")
except NumberTooSmallError as e:
print("Exception:", e)
Q56. Write a program that accepts data of birth along with personal details of a person.
Raise an exception if invalid date is entered.
Ans. class InvalidDateError(Exception):
def is_valid_date(day, month, year):
if year < 1 or month < 1 or month > 12 or day < 1:
return False
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
month_days[1] = 29
if day > month_days[month - 1]:
return False
return True
try:
name = input("Enter Name: ")
address = input("Enter Address: ")
day = int(input("Enter Birth Day: "))
month = int(input("Enter Birth Month: "))
year = int(input("Enter Birth Year: "))
if not is_valid_date(day, month, year):
raise InvalidDateError("Invalid date entered")
print("\nDetails Stored Successfully:")
print("Name:", name)
print("Address:", address)
print("Date of Birth:", f"{day}-{month}-{year}")
except ValueError:
print("Invalid input. Please enter numbers for day, month, and year.")
except InvalidDateError as e:
print(e)
ASSIGNMENT – 13
[Link] a program in Python to create a Pandas Series.
Ans. import pandas as pd
data = [10, 20, 30, 40, 50]
s = [Link](data)
print("Pandas Series:")
print(s)
[Link] a program in Python to display the first five and last five rows of a DataFrame.
Ans. import pandas as pd
data = { "Name": ["A", "B", "C", "D", "E", "F", "G"], "Age": [21, 22, 23, 24, 25, 26, 27] }
df = [Link](data)
print("First five rows:")
print([Link]())
print("\nLast five rows:")
print([Link]())
[Link] a program in Python to read data from a CSV file using Pandas.
Ans. import pandas as pd
df = pd.read_csv("[Link]") # replace with your file name
print("CSV Data:")
print(df)
Q60. Write a program in Python to select:
i)select a specific column from a DataFrame
[Link](df[“Name”])
ii)select multiple columns from a DataFrame
Ans. print(df[“Name”,”Marks”])
iii)retrieve a row by its index label
Ans. Print([Link][“s3”])
iv) using rows based on conditions (e.g., marks > 80).
Ans. print(df[df["Marks"] > 80])
ASSIGNMENT – 14
Q61. Plot a simple line graph, scatter plot, Bar chart, Histogram, Bar chart (e.g., student
scores), Pie chart (percentage categories).
Ans. Line Graph
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [3, 7, 4, 9, 2]
[Link](x, y)
[Link]("Simple Line Graph")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()
Scatter Plot
import [Link] as plt
x = [10, 20, 30, 40]
y = [5, 25, 35, 10]
[Link](x, y)
[Link]("Scatter Plot")
[Link]("X")
[Link]("Y")
[Link]()
Bar Graph
import [Link] as plt
students = ["A", "B", "C", "D"]
scores = [85, 92, 76, 88]
[Link](students, scores)
[Link]("Student Scores")
[Link]("Students")
[Link]("Marks")
[Link]()
Histogram
import [Link] as plt
data = [10,20,20,30,30,30,40,40,50,60,60,60,70]
[Link](data, bins=5)
[Link]("Histogram Example")
[Link]("Value Range")
[Link]("Frequency")
[Link]()
Pie Chart
import [Link] as plt
categories = ["Sports", "Study", "Sleep", "Mobile"]
hours = [2, 6, 8, 4]
[Link](hours, labels=categories, autopct="%1.1f%%")
[Link]("Daily Time Distribution")
[Link]()
Q62. Plot multiple lines on one graph and customize plots (labels, title, legend)..
Ans. import [Link] as plt
days = [1, 2, 3, 4, 5]
s1 = [10, 20, 15, 30, 25]
s2 = [5, 10, 20, 25, 30]
[Link](days, s1, label="Class A")
[Link](days, s2, label="Class B")
[Link]("Days")
[Link]("Scores")
[Link]("Performance Comparison")
[Link]()
[Link]()
Q63. Create and print a NumPy array and Generate an array of even numbers and odd
numbers.
Ans. import numpy as np
arr = [Link]([10, 20, 30, 40])
even_arr = [Link](2, 21, 2)
odd_arr = [Link](1, 20, 2)
print(arr)
print(even_arr)
print(odd_arr)
Q64. Create a 2D array and access elements.
Ans. import numpy as np
arr2d = [Link]([[10, 20, 30], [40, 50, 60]])
print("Full Array:")
print(arr2d)
print("Element at row1,col2:", arr2d[0][1])
print("Second row:", arr2d[1])
print("First column:", arr2d[:, 0])
Q65. Programs based on GUI (module Tkinter) i)Create a simple Tkinter window ii)Create a
window with a label iii)Create a window with a button iv)Create a window with multiple
widgets (Label, Button, Entry) v)Change label text when a button is clicked.
Ans. import tkinter as tk
def change_text():
label_main.config(text="Button Clicked!")
root = [Link]()
[Link]("Q5 - Tkinter Combined Program")
[Link]("300x250")
label_main = [Link](root, text="Hello Tkinter!", font=("Arial", 12))
label_main.pack(pady=10)
button_simple = [Link](root, text="Simple Button")
button_simple.pack(pady=5)
label_name = [Link](root, text="Enter your name:")
label_name.pack()
entry_name = [Link](root)
entry_name.pack()
button_submit = [Link](root, text="Submit")
button_submit.pack(pady=5)
button_change = [Link](root, text="Click to Change Text", command=change_text)
button_change.pack(pady=10)
[Link]()
PYTHON MINI PROJECT
Title: WORDLE
1. Introduction
This project is a Python-based recreation of the popular word-guessing game Wordle. The
main goal was to design an interactive game environment using Pygame, implement the
core logic behind word validation and color-coded hints, and provide a smooth, user-friendly
graphical interface.
The project demonstrates strong fundamentals of Python programming, event handling, file
operations, and game design logic. It also shows how simple algorithms can be combined
with UI rendering to build a completely functional mini-game.
2. TechStack Used
Programming Language: Python
Library Used: Pygame (for graphics, rendering, and event handling)
Topics Covered:
Random Module
File handling
Lists
[Link] Code
[Link]
import random
import pygame
def load_dictionary(file_name):
file = open(file_name)
words = [Link]()
[Link]()
return [word[:5].upper() for word in words] #only keep the first 5
letters
answers = load_dictionary("[Link]")
possible_answers = load_dictionary("[Link]")
curr_answer = [Link](answers)
print(curr_answer)
width = 600
height = 700
margin_top = 100
margin_bottom = 100
margin_left = 100
margin_top = 150
margin = 10
sq_size = 60
user_input = ""
guesses = []
alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
unguessed = alphabets
game_over = False
def find_unguessed_letters(guesses):
ans = ""
my_set = set()
for s in guesses:
for char in s:
my_set.add(char)
for a in alphabets:
if a not in my_set:
ans+=a
return ans
def determine_color(guess, j):
letter = guess[j]
if letter == curr_answer[j]:
return green
elif letter in curr_answer:
totalCount = curr_answer.count(letter)
posCorrect = 0
totalOccurence = 0
for i in range(5):
# a correct letter has been guessed
if guess[i] == letter:
#correct at correct pos
if i<=j:
totalOccurence+=1
if guess[i] == curr_answer[i]:
posCorrect+=1
if totalCount-posCorrect>0:
return yellow
else:
return grey
else:
return grey
[Link]()
[Link]()
[Link].set_caption("Wordle")
screen = [Link].set_mode((width, height))
grey = (70, 70, 80)
green = (6,214,160)
yellow = (255, 209, 102)
font = [Link]("freesansbold", sq_size)
font_small = [Link]("freesansbold", sq_size // 2)
#animation loop
animating = True
while animating:
#background
[Link]("white")
letters = font_small.render(unguessed, False, grey)
surface = letters.get_rect(center = (width//2, margin_top//2))
[Link](letters, surface)
#start guessing
y = margin_top
#the game is played 6 times
for i in range(6):
x = margin_left
#every word has 5 letters
for j in range(5):
square = [Link](x, y, sq_size, sq_size)
[Link](screen, grey, square, width=2,
border_radius=3)
#there is atleast one word that is guessed
if len(guesses) > i:
color = determine_color(guesses[i], j)
[Link](screen, color, square,
border_radius=3)
letter = [Link](guesses[i][j], False, (255,255,
255))
surface = letter.get_rect(center = (x+sq_size//2,
y+sq_size//2))
[Link](letter, surface)
#displaying the current word being guessed
if i==len(guesses) and j<len(user_input):
letter = [Link](user_input[j], False, grey)
surface = letter.get_rect(center = (x+sq_size//2,
y+sq_size//2))
[Link](letter, surface)
x += sq_size + margin
y+=sq_size+margin
# printing the correct answer or result
if game_over or len(guesses) == 6:
if game_over or (len(guesses) > 0 and guesses[-1] ==
curr_answer):
message = "Congratulations, you won!"
else:
message = f"The correct word was: {curr_answer}"
letter = [Link](message, False, grey)
surface = letter.get_rect(center=(width//2, height -
margin_bottom//2))
[Link](letter, surface)
[Link]()
#getting user interactions
for event in [Link]():
#closing the window stops the animation
if [Link] == [Link]:
animating = False
# user is interacting by pressing keys
elif [Link] == [Link]:
if [Link] == pygame.K_ESCAPE:
animating = False
elif [Link] == pygame.K_RETURN:
#dont take anything less than 5
if len(user_input) == 5 and user_input in
possible_answers:
[Link](user_input)
unguessed = find_unguessed_letters(guesses)
game_over = True if user_input == curr_answer else
False
user_input = ""
#backspace functionality
elif [Link] == pygame.K_BACKSPACE:
if(len(user_input)>0):
user_input = user_input[0:len(user_input)-1]
elif len(user_input)<5 and not game_over:
user_input = user_input + [Link]()
print(user_input)