PANIMALAR ENGINEERING COLLEGE
(An Autonomous Institution, Affiliated to Anna University, Chennai)
ANSWER KEY
Name of the Course PROGRAMMING IN PYTHON
Course Code 23ES1206
Regulation 2023
Semester II
UNIT – V
PACKAGES AND GUI
PART A – 2 MARKS
Q1. [2 Marks] Define Python package and mention its importance.
Answer:
A package is a directory containing a collection of related Python modules and an __init__.py file. Importance:
• Organises related modules into a namespace.
• Promotes code reuse and modular design.
• Avoids naming conflicts between modules.
• Examples: NumPy, Pandas, Matplotlib, Tkinter.
Q2. [2 Marks] What is NumPy? State two advantages over Python lists.
Answer:
NumPy (Numerical Python) is a package for scientific computing. It provides the ndarray (n-dimensional array)
object.
• Faster computation — operations on NumPy arrays are implemented in C.
• Memory efficient — stores elements of same type contiguously.
• Supports vectorised operations — no need for explicit loops.
Q3. [2 Marks] Define Series and DataFrame in Pandas.
Answer:
Series: A one-dimensional labeled array capable of holding any data type. Like a column in a spreadsheet.
import pandas as pd
s = [Link]([10, 20, 30], index=['a','b','c'])
DataFrame: A two-dimensional, table-like data structure with labeled rows and columns.
df = [Link]({'Name':['Alice','Bob'],'Age':[20,21]})
Q4. [2 Marks] What function is used in Matplotlib to plot a basic line graph?
Answer:
The [Link]() function is used to plot a basic line graph.
import [Link] as plt
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
[Link](x, y)
[Link]('Line Graph')
[Link]('X-axis')
[Link]('Y-axis')
[Link]()
Q5. [2 Marks] Write the syntax to create a Pandas Series.
Answer:
import pandas as pd
# From list
s1 = [Link]([10, 20, 30, 40])
# With custom index
s2 = [Link]([10, 20, 30], index=['a', 'b', 'c'])
# From dictionary
s3 = [Link]({'x': 1, 'y': 2, 'z': 3})
Q6. [2 Marks] What is Tkinter in Python?
Answer:
Tkinter is Python's standard GUI (Graphical User Interface) toolkit. It provides a fast and easy way to create
GUI applications using a set of widgets (buttons, labels, text boxes, etc.). It is built on top of the Tk GUI toolkit
and comes pre-installed with Python.
Q7. [2 Marks] What is the purpose of Matplotlib?
Answer:
Matplotlib is a comprehensive Python library for creating static, animated, and interactive visualizations. It is
used to plot:
• Line graphs, Bar charts, Histograms
• Scatter plots, Pie charts, Box plots
• 3D plots, Heat maps
It is widely used in data analysis and scientific computing.
Q8. [2 Marks] Name any two Tkinter widgets and their purposes.
Answer:
• Label – Displays text or an image (non-editable). Example: Label(root, text='Hello')
• Button – Triggers an action/command when clicked. Example: Button(root, text='Click Me',
command=func)
• Entry – Single-line text input field.
Q9. [2 Marks] What advantages does Tkinter offer for GUI-based Python applications?
Answer:
• Built into Python standard library — no separate installation needed.
• Cross-platform — runs on Windows, macOS, and Linux.
• Simple and easy to learn for beginners.
• Provides rich set of widgets for building complete GUI apps.
Q10. [2 Marks] What is the role of NumPy when creating a Pandas Series?
Answer:
Pandas is built on top of NumPy. When creating a Pandas Series, NumPy arrays serve as the underlying data
structure. NumPy's NaN (Not a Number) is used to represent missing values in a Series.
import numpy as np
import pandas as pd
arr = [Link]([1, 2, [Link], 4])
s = [Link](arr)
print(s)
PART B – 13 MARKS
Q1. [13 Marks] Pandas DataFrame from 2D list and data manipulation
Answer:
import pandas as pd
# Create DataFrame from 2D list
data = [['Alice', 85, 90, 78],
['Bob', 72, 65, 88],
['Charlie', 91, 87, 95],
['Diana', 68, 74, 80]]
cols = ['Name', 'Math', 'Science', 'English']
df = [Link](data, columns=cols)
print('Original DataFrame:')
print(df)
# Data manipulation
df['Total'] = df['Math'] + df['Science'] + df['English']
df['Average'] = df['Total'] / 3
print('\nWith Total and Average:')
print(df)
# Statistics
print('\nDescriptive Statistics:')
print([Link]())
print('\nStudent with highest average:', [Link][df['Average'].idxmax(), 'Name'])
print('Class average:', df['Average'].mean().round(2))
# Filter
print('\nStudents scoring above 80 average:')
print(df[df['Average'] > 80][['Name', 'Average']])
Q2. [13 Marks] Bar Charts vs Histograms in Matplotlib
Answer:
Bar Chart: Used for categorical data. Each bar represents a category. Bars are separated.
Histogram: Used for continuous numerical data. Bars are adjacent, showing frequency distribution in bins.
Comparison:
• Bar chart: categories on X-axis; Histogram: numerical ranges.
• Bar chart: bars have gaps; Histogram: bars are touching.
• Bar chart: shows comparison; Histogram: shows distribution.
Parameters: bins (histogram), labels, width, color, align, edgecolor.
import [Link] as plt
import numpy as np
# --- Bar Chart ---
categories = ['Math', 'Science', 'English', 'History', 'Python']
scores = [85, 72, 91, 68, 95]
[Link](figsize=(10, 4))
[Link](1, 2, 1)
[Link](categories, scores, color='steelblue', edgecolor='black', width=0.5)
[Link]('Subject Scores - Bar Chart')
[Link]('Subject')
[Link]('Score')
[Link](0, 100)
# --- Histogram ---
marks = [Link](40, 100, 50) # 50 random marks
[Link](1, 2, 2)
[Link](marks, bins=10, color='salmon', edgecolor='black')
[Link]('Marks Distribution - Histogram')
[Link]('Marks Range')
[Link]('Frequency')
plt.tight_layout()
[Link]()
Q3. [13 Marks] GUI programming and Tkinter widgets. Simple window + login form
Answer:
GUI Programming: Creating applications with graphical elements (windows, buttons, menus) instead of
text-based interfaces. Tkinter is Python's built-in GUI toolkit.
Common Tkinter widgets:
• Label – display text/images
• Button – clickable element that triggers a function
• Entry – single-line text input
• Frame – container to organise widgets
• Text – multi-line text area
• Checkbutton, Radiobutton – selection widgets
# Simple GUI Window
from tkinter import *
root = Tk()
[Link]('Simple Window')
[Link]('300x150')
lbl = Label(root, text='Welcome to Tkinter!', font=('Arial', 14))
[Link](pady=20)
def on_click():
[Link](text='Button Clicked!')
btn = Button(root, text='Click Me', command=on_click, bg='blue', fg='white')
[Link]()
[Link]()
# Login Form
from tkinter import *
from tkinter import messagebox
def login():
u = [Link]()
p = [Link]()
if u == 'admin' and p == '1234':
[Link]('Login', 'Login Successful!')
else:
[Link]('Login', 'Invalid credentials!')
root = Tk()
[Link]('Login Form')
[Link]('300x200')
Label(root, text='Username:').grid(row=0, column=0, pady=10, padx=10)
username = Entry(root)
[Link](row=0, column=1)
Label(root, text='Password:').grid(row=1, column=0, pady=10, padx=10)
password = Entry(root, show='*')
[Link](row=1, column=1)
Button(root, text='Login', command=login, width=10).grid(row=2, columnspan=2, pady=15)
[Link]()
Q4. [13 Marks] Evaluate NumPy code and fix error; benefits; broadcasting
Answer:
i) Error and correction:
Given: a = [Link](10,20,30)
Error: [Link]() expects a single iterable (list/tuple) as argument, not multiple arguments.
import numpy as np
# Corrected:
a = [Link]([10, 20, 30]) # list passed as single argument
b = [Link]([1, 2, 3])
c = a + b
print(c) # [11 22 33]
ii) Benefits of NumPy over Python lists:
• Faster computation using vectorised operations (no loops needed).
• Less memory — homogeneous dtype.
• Supports multi-dimensional arrays and matrix operations.
• Rich mathematical functions: mean, std, dot, linalg, etc.
iii) Broadcasting:
Broadcasting allows NumPy to perform operations on arrays of different shapes by expanding (broadcasting)
the smaller array to match the larger one.
import numpy as np
a = [Link]([[1,2,3],[4,5,6]])
b = [Link]([10, 20, 30]) # shape (3,) broadcasts to (2,3)
print(a + b)
# [[11 22 33]
# [14 25 36]]
Q5. [13 Marks] Pandas Series using NumPy and basic operations
Answer:
import numpy as np
import pandas as pd
# Create NumPy array
marks_array = [Link]([85, 72, 91, 68, 95, 77, 83])
# Create Pandas Series
students = ['Alice','Bob','Charlie','Diana','Eve','Frank','Grace']
marks_series = [Link](marks_array, index=students)
print('Marks Series:')
print(marks_series)
# Basic operations
print('\nMax marks:', marks_series.max())
print('Min marks:', marks_series.min())
print('Mean marks:', marks_series.mean())
print('Std deviation:', marks_series.std().round(2))
print('Median:', marks_series.median())
# Filter
print('\nStudents scoring above 80:')
print(marks_series[marks_series > 80])
# Sort
print('\nSorted by marks:')
print(marks_series.sort_values(ascending=False))
# Arithmetic
bonus = [Link]([Link](7, 5), index=students) # add 5 bonus marks
final = marks_series + bonus
print('\nAfter bonus:')
print(final)
Q6. [13 Marks] Tkinter Student Mark Sheet GUI
Answer:
from tkinter import *
from tkinter import messagebox
def calculate():
try:
name = name_var.get()
roll = roll_var.get()
subjects = ['Math','Science','English','History','Python']
marks = [float([Link]()) for m in mark_vars]
for m in marks:
if m < 0 or m > 100:
raise ValueError('Marks must be 0-100')
total = sum(marks)
avg = total / len(marks)
grade = 'O' if avg>=90 else 'A+' if avg>=80 else 'A' if avg>=70 else \
'B+' if avg>=60 else 'B' if avg>=50 else 'C' if avg>=40 else 'F'
result = f'Name: {name} Roll: {roll}\n'
for s, m in zip(subjects, marks):
result += f'{s}: {m}\n'
result += f'Total: {total}/500 Avg: {avg:.2f} Grade: {grade}'
[Link]('Mark Sheet', result)
except ValueError as e:
[Link]('Error', str(e))
root = Tk()
[Link]('Student Mark Sheet')
[Link]('350x380')
Label(root,text='Student Mark
Sheet',font=('Arial',14,'bold')).grid(row=0,columnspan=2,pady=10)
name_var = StringVar()
roll_var = StringVar()
Label(root,text='Name:').grid(row=1,column=0,sticky='e',padx=10)
Entry(root,textvariable=name_var).grid(row=1,column=1,pady=5)
Label(root,text='Roll No:').grid(row=2,column=0,sticky='e',padx=10)
Entry(root,textvariable=roll_var).grid(row=2,column=1,pady=5)
subjects=['Math','Science','English','History','Python']
mark_vars=[]
for i,sub in enumerate(subjects,3):
Label(root,text=f'{sub}:').grid(row=i,column=0,sticky='e',padx=10)
v=StringVar()
Entry(root,textvariable=v).grid(row=i,column=1,pady=3)
mark_vars.append(v)
Button(root,text='Calculate',command=calculate,bg='green',fg='white').grid(row=8,columnsp
an=2,pady=15)
[Link]()
Q7. [13 Marks] Discuss various Tkinter widgets with examples
Answer:
Tkinter provides many widgets for building GUI applications:
• Label – displays non-editable text or image.
• Button – performs action on click via command parameter.
• Entry – single-line text input field.
• Text – multi-line text editing widget.
• Frame – container to group other widgets.
• Checkbutton – on/off toggle checkbox.
• Radiobutton – mutually exclusive option selection.
• Listbox – scrollable list of items for selection.
• Scrollbar – scrolling for other widgets.
• Scale – slider for selecting numeric value.
• Menu – dropdown menu bar.
• Canvas – drawing shapes, images, graphics.
• Messagebox – popup dialogs (info, warning, error).
from tkinter import *
root = Tk()
[Link]('Widget Demo')
[Link]('400x350')
# Label
Label(root, text='Label Widget', fg='blue').pack(pady=5)
# Entry
entry = Entry(root, width=30)
[Link](pady=5)
# Button
Button(root, text='Click Me', command=lambda: print('Clicked!')).pack(pady=5)
# Checkbutton
chk_var = BooleanVar()
Checkbutton(root, text='Accept Terms', variable=chk_var).pack(pady=5)
# Radiobutton
rad_var = StringVar(value='Python')
for lang in ['Python','Java','C++']:
Radiobutton(root, text=lang, variable=rad_var, value=lang).pack()
# Listbox
lb = Listbox(root, height=3)
for item in ['Apple','Banana','Cherry']:
[Link](END, item)
[Link](pady=5)
# Scale
Scale(root, from_=0, to=100, orient=HORIZONTAL).pack(pady=5)
[Link]()
PART C – 15 MARKS
Q1. [15 Marks] Tkinter Calendar GUI: enter year and month
Answer:
import calendar
from tkinter import *
from tkinter import messagebox
def show_calendar():
try:
year = int(year_entry.get())
month = int(month_entry.get())
if month < 1 or month > 12:
raise ValueError('Month must be 1-12')
cal_text = [Link](year, month)
cal_display.config(state=NORMAL)
cal_display.delete('1.0', END)
cal_display.insert('1.0', cal_text)
cal_display.config(state=DISABLED)
except ValueError as e:
[Link]('Error', str(e))
root = Tk()
[Link]('Calendar Application')
[Link]('350x350')
Label(root, text='Calendar Viewer', font=('Arial',14,'bold')).pack(pady=10)
frame = Frame(root)
[Link](pady=5)
Label(frame, text='Year:').grid(row=0, column=0, padx=5)
year_entry = Entry(frame, width=8)
year_entry.grid(row=0, column=1)
Label(frame, text='Month (1-12):').grid(row=0, column=2, padx=5)
month_entry = Entry(frame, width=4)
month_entry.grid(row=0, column=3)
Button(root, text='Show Calendar', command=show_calendar, bg='blue',
fg='white').pack(pady=10)
cal_display = Text(root, height=10, width=30, font=('Courier',10), state=DISABLED)
cal_display.pack(padx=10, pady=5)
[Link]()
Q2. [15 Marks] End-to-end data analysis: NumPy + Pandas + Matplotlib
Answer:
import numpy as np
import pandas as pd
import [Link] as plt
# --- NumPy array of marks ---
marks_array = [Link]([85, 72, 91, 68, 95, 77, 83, 60, 88, 74])
s = [Link](marks_array, name='Marks')
print('Pandas Series:')
print(s)
# --- DataFrame ---
data_2d = [['Alice', 101, 85],
['Bob', 102, 72],
['Charlie', 103, 91],
['Diana', 104, 68],
['Eve', 105, 95],
['Frank', 106, 77],
['Grace', 107, 83]]
df = [Link](data_2d, columns=['Name','Roll No','Marks'])
print('\nDataFrame:')
print(df)
# Add Grade column
def assign_grade(m):
return 'O' if m>=90 else 'A+' if m>=80 else 'A' if m>=70 else 'B+' if m>=60 else 'B'
df['Grade'] = df['Marks'].apply(assign_grade)
# Handle missing values (demo)
[Link][2,'Marks'] = [Link]
df['Marks'].fillna(df['Marks'].mean(), inplace=True)
print('\nWith Grade and filled NaN:')
print(df)
# --- Matplotlib plots ---
fig, axes = [Link](1, 2, figsize=(12, 5))
# Bar chart
axes[0].bar(df['Name'], df['Marks'], color='steelblue', edgecolor='black')
axes[0].set_title('Student Marks - Bar Chart')
axes[0].set_xlabel('Student')
axes[0].set_ylabel('Marks')
axes[0].set_ylim(0,100)
for i, (_, row) in enumerate([Link]()):
axes[0].text(i, row['Marks']+1, f"{row['Marks']:.0f}", ha='center', fontsize=8)
# Line chart
axes[1].plot(df['Name'], df['Marks'], marker='o', color='green', linewidth=2)
axes[1].set_title('Marks Progression - Line Chart')
axes[1].set_xlabel('Student')
axes[1].set_ylabel('Marks')
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
[Link]('student_analysis.png')
[Link]()
print('\nCharts saved as student_analysis.png')
Visualizations support faster identification of high/low performers, trend analysis, and grade distribution — far
more efficient than reading raw numbers.
Q3. [15 Marks] Evaluate Tkinter file browser program
Answer:
i) Analysis of the given program:
The program uses [Link]() to open a native file browser dialog. The selected file
path is displayed on a Label.
• Tk() creates the main window.
• Button with command=browse_file triggers file dialog.
• [Link]() returns the selected file path as a string.
• [Link](text=...) updates the label dynamically.
• [Link]() keeps the window running.
ii) Modified program — GUI-based file explorer:
from tkinter import *
import [Link] as fd
import os
def browse_file():
filename = [Link](
title='Select a file',
filetypes=[('Text files','*.txt'),('All files','*.*')]
)
if filename:
[Link](text='Selected: ' + filename)
try:
with open(filename, 'r') as f:
content = [Link]()
text_area.config(state=NORMAL)
text_area.delete('1.0', END)
text_area.insert('1.0', content)
text_area.config(state=DISABLED)
size = [Link](filename)
info_lbl.config(text=f'Size: {size} bytes')
except Exception as e:
[Link](text=f'Error: {e}')
root = Tk()
[Link]('File Explorer')
[Link]('500x400')
Label(root, text='GUI File Explorer', font=('Arial',13,'bold')).pack(pady=8)
Button(root, text='Browse File', command=browse_file, bg='blue', fg='white').pack()
lbl = Label(root, text='No file selected', wraplength=450, fg='gray')
[Link](pady=3)
info_lbl = Label(root, text='', fg='green')
info_lbl.pack()
text_area = Text(root, height=14, state=DISABLED, font=('Courier',9))
text_area.pack(padx=10, fill=BOTH, expand=True)
[Link]()
iii) Advantages of GUI-based file explorers:
• User-friendly — no need to type file paths; users navigate visually.
• Cross-platform — works on Windows, macOS, Linux.
• Reduces errors — users browse and select, reducing typos.
Real-world applications:
• File managers (Windows Explorer, macOS Finder) — browse, copy, move files.
• IDEs (VS Code, PyCharm) — open, edit, and manage project files visually.