BCC302 · Python Programming · Unit 5
Python packages
Unit Scope & Exam Weightage: This unit turns Python into a practical tool: built-in functions of matplotlib, NumPy arrays and matrix operations, pandas DataFrame/CSV handling, Tkinter widgets and event handling, Tkinter examples, and Python programming with IDE. The supplied question set has 24 recorded clusters (about 138 marks): plotting programs dominate, so keep four import-and-plot skeletons ready, plus one small Tkinter window program.
Front Page: Importance-Wise Topic Roadmap (2023–26 PYQs)
| Priority | Topic (Exact Syllabus) | PYQs Asked | Marks Weightage | Tag |
|---|---|---|---|---|
| 1 | Simple programs using the built-in functions of packages matplotlib | 13 (2023-24 ×10, 2024-25 ×2, 2025-26) |
7m ×10 + 2m ×3 = 76m | Survival Mode |
| 2 | Tk Widgets | 3 (2025-26 ×2, 2024-25) |
7m ×2 + 2m = 16m | GUI Bank |
| 3 | pandas etc | 2 (2024-25 ×2) |
7m ×2 = 14m | CSV Handling |
| 4 | GUI Programming: Tkinter introduction | 2 (2024-25, 2025-26) |
7m ×2 = 14m | GUI Bank |
| 5 | numpy | 2 (2024-25, 2025-26) |
7m + 2m = 9m | Array Maths |
| 6 | Tkinter examples | 1 (2023-24) |
7m | Calculator |
| 7 | Python programming with IDE | 1 (2025-26) |
2m | Quick Theory |
| 8 | Tkinter and PythonProgramming | 0 (—) | — | Integrated |
2-Hour Last-Night Survival Checklist:
- Matplotlib skeleton (Priority 1):
import matplotlib.pyplot as plt→ preparexandy→plt.plot(x,y,marker='o')→title/xlabel/ylabel/legend/grid→plt.show(). Change only the plot command for bar/pie. - NumPy essentials (Priority 5):
np.array,np.zeros,np.eye(3),np.arange(a,b,step),np.linspace(a,b,n),A @ B,A.T,np.linalg.inv(A),np.random.randint(10,51,5). - Pandas CSV pattern (Priority 3):
df = pd.read_csv('file.csv')→ filter withdf[df[col] > t]→ compute withdf.mean(numeric_only=True)→print(df). - Tkinter four lines (Priority 2/4/6):
root = Tk()→ create widget withLabel(root, text=...).pack()→root.mainloop(); bind an event withwidget.bind('<Button-1>', handler). - 2-Mark definitions: IDE = editor + interpreter + debugger in one tool; package = folder of reusable modules; widget = GUI control such as Button, Label or Entry.
1. Python Packages and the IDE
Package: A folder/collection of Python modules that can be imported to reuse tested code. A package is imported with import package or from package import function; an optional alias keeps long names short, e.g. import numpy as np.
IDE (Integrated Development Environment): A single application combining a source-code editor, file/project manager, interpreter/console, debugger and often an integrated terminal. Examples: IDLE, PyCharm, VS Code, Spyder, Jupyter.
| Package | Main purpose | Most-used import |
|---|---|---|
numpy |
Fast arrays, matrices, linear algebra, random numbers | import numpy as np |
pandas |
Table-like data handling through Series and DataFrame |
import pandas as pd |
matplotlib |
2-D plots: line, bar, pie, histogram, scatter | import matplotlib.pyplot as plt |
tkinter |
Standard-library GUI toolkit | from tkinter import * |
Three ways to import:
import math # use math.sqrt(25)
import math as m # use m.sqrt(25)
from math import sqrt # use sqrt(25)
Python Packages Examiner Tip: In "purpose of packages" answers, give one concrete line of code for each package. A table with name → import → one function earns more than a paragraph of general description.
After-Topic PYQs:
- 2025-26 (Sec A, 2 Marks): "What is an IDE in Python programming?"
- 2025-26 (Sec C, 7 Marks): "What are Python packages? Explain the purpose of packages like NumPy, Pandas, and Matplotlib."
- 2024-25 (Sec C, 7 Marks): "How do we use packages in Python programming? Explain the use of pandas."
- 2023-24 (Sec A, 2 Marks): "Describe the difference between linspace and argspace."
- 2024-25 (Sec A, 2 Marks): "Explain why numpy is used instead of python arrays for mathematical calculations."
Short answers to the 2-mark questions:
- IDE: one tool for writing, running and debugging Python code; IDLE ships with Python.
linspacevsarange(the PYQ writes "argspace"):np.linspace(a,b,n)returns exactly n evenly spaced samples including both ends;np.arange(a,b,step)builds values fromato just beforebwith a fixed step, so the count depends on the step.- Why NumPy over Python lists: NumPy stores homogeneous data in contiguous memory as a C array, so vectorised operations run without Python-level loops; it also supplies shape, broadcasting, linear algebra and random-number functions. A Python list can hold mixed types and needs explicit loops.
2. NumPy: Arrays, Matrices and Random Numbers
ndarray: NumPy's n-dimensional array object. All elements have the same dtype, the shape is available as a.shape, and arithmetic is applied element-by-element unless matrix multiplication @ is used.
Core NumPy constructors: np.array([1,2,3]), np.zeros((2,3)), np.ones((3,3)), np.eye(3) (identity matrix), np.arange(10,50,5), np.linspace(0,1,5), np.random.randint(10,51,5).
import numpy as np
A = np.array([[1, 2],
[3, 4]])
B = np.array([[5, 6],
[7, 8]])
print(A + B) # element-wise addition → [[ 6 8],[10 12]]
print(A * B) # element-wise product → [[ 5 12],[21 32]]
print(A @ B) # matrix product → [[19 22],[43 50]]
print(A.T) # transpose → [[1 3],[2 4]]
print(np.eye(3)) # 3x3 identity matrix
print(np.linalg.det(A)) # -2.0
Matrix inverse check: for a square non-singular matrix, A @ np.linalg.inv(A) gives the identity matrix. Always mention that division by a zero determinant is not allowed.
import numpy as np
rng = np.random.default_rng() # modern reproducible generator
print(rng.integers(10, 51, 5)) # 5 random integers in [10, 50]
# Older exam style:
print(np.random.randint(10, 51, 5)) # high value 51 is excluded
NumPy Examiner Tip: For randint(10, 50, 5) the upper limit is exclusive, so valid answers lie from 10 to 49. To include 50, write randint(10, 51, 5). State this explicitly; it is a common marking point.
After-Topic PYQs:
- 2024-25 (Sec C, 7 Marks): "Write a Python program using numpy to perform matrix operations."
- 2023-24 (Sec C, 7 Marks): "Describe how to generate random numbers using NumPy. Write a Python program to create an array of random integers between and ."
- 2023-24 (Sec A, 2 Marks): "Which function is used to create identity matrix in NumPy?" (Ans:
np.eye(n))
3. Matplotlib: Line, Pie and Dataset Plots
Matplotlib: A plotting library whose matplotlib.pyplot module provides a MATLAB-like state machine. plt.plot() draws line charts, plt.bar() bar charts, plt.pie() pie charts, plt.scatter() scatter plots and plt.hist() histograms.
3.1 Universal Plot Skeleton
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
plt.plot(x, y, marker='o', color='blue', linewidth=2, label='Series 1')
plt.title('Simple Line Graph')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.legend()
plt.grid(True)
plt.show()
| Function | Job in an exam program |
|---|---|
plt.plot(x,y) |
line plot; marker='o' marks data points |
plt.bar(x,y) |
vertical bar chart |
plt.pie(values, labels=names, autopct='%1.1f%%') |
pie chart with percentage labels |
plt.scatter(x,y) |
scatter plot |
plt.title / xlabel / ylabel |
labels worth one mark each |
plt.legend() / plt.grid(True) |
legend and grid |
plt.show() |
opens the figure window; omit it in Jupyter if %matplotlib inline is used |
3.2 Pie Chart Data from the PYQ
| Language | Python | Java | C++ | JavaScript | Ruby |
|---|---|---|---|---|---|
| Popularity | 30 | 25 | 20 | 15 | 10 |
Total popularity = 30 + 25 + 20 + 15 + 10 = 100, so each value is already a percentage: 30%, 25%, 20%, 15%, 10%.
import matplotlib.pyplot as plt
languages = ['Python', 'Java', 'C++', 'JavaScript', 'Ruby']
popularity = [30, 25, 20, 15, 10]
plt.pie(popularity, labels=languages, autopct='%1.1f%%', startangle=90)
plt.title('Language Popularity')
plt.axis('equal') # keeps the pie circular
plt.show()
3.3 CSV and Multi-Column Data
For cities.csv, use pandas or the csv module, separate the last column, and plot the first two columns:
import csv
import matplotlib.pyplot as plt
rows = []
with open('cities.csv', 'r', newline='', encoding='utf-8') as f:
for row in csv.reader(f):
rows.append(row)
last_col = [r[-1] for r in rows] # saved separately
data = [r[:-1] for r in rows] # last column removed
x = [r[0] for r in data[1:]] # assume first row is a header
y = [float(r[1]) for r in data[1:]]
plt.plot(x, y, marker='o')
plt.xlabel('First column (city)')
plt.ylabel('Second column')
plt.xticks(rotation=45)
plt.show()
Matplotlib Examiner Tip: A full-mark plot answer contains five visible items: data arrays, one plot call, title, axis labels, and plt.show(). Add legend() and grid(True) when comparing two series.
After-Topic PYQs:
- 2025-26 (Sec C, 7 Marks): "How is Matplotlib used in Python? Write a program to plot a simple line graph."
- 2024-25 (Sec C, 7 Marks): "Create a pie chart using matplotlib to represent the following data: Languages: Python, Java, C++, JavaScript, Ruby; Popularity: 30, 25, 20, 15, 10."
- 2024-25 (Sec C, 7 Marks): "Explain the use of matplotlib for data visualization. Write a program to visualize Line plots using these data: x = [1, 2, 3, 4, 5], y = [10, 20, 25, 30, 40]"
- 2023-24 (Sec C, 7 Marks): "Explain the basic usage of matplotlib for plotting graphs. Write a Python program to plot a simple line graph showing the relationship between and ."
- 2023-24 (Sec C, 7 Marks): "Construct a plot for following dataset using matplotlib: Food | Calories | Potassium | fat Meat | 250 | 40 | 8 Banana | 130 | 55 | 5 Avocados | 140 | 20 | 3 Sweet Potatoes | 120 | 30 | 6 Spinach | 20 | 40 | 1 Watermelon | 20 | 32 | 1.5 Coconut water | 10 | 10 | 0 Beans | 50 | 26 | 2 Legumes | 40 | 25 | 1.5 Tomato | 19 | 20 | 2.5"
- 2023-24 (Sec C, 7 Marks): "Construct a program to read cities.csv dataset, remove last column and save it in an array. Save the last column to another array. Plot the first two columns."
- 2023-24 (Sec A, 2 Marks): "Describe about different functions of matplotlib and pandas."
Dataset plot pattern (food data): store the food names in labels, calories in calories, then use a bar chart: plt.bar(labels, calories), plt.xticks(rotation=45). To compare calories and potassium on the same figure use two subplots with plt.subplots(2,1) or a scatter plot of calories versus potassium.
4. Pandas: Series, DataFrame and CSV Filtering
Series: a one-dimensional labelled array.
DataFrame: a two-dimensional labelled table with rows (index) and columns (Series). It is the pandas equivalent of a spreadsheet or SQL table.
import pandas as pd
data = {'Name': ['Asha', 'Ravi', 'Meera'],
'Marks': [88, 72, 95],
'City': ['Lucknow', 'Kanpur', 'Noida']}
df = pd.DataFrame(data)
print(df)
print(df['Marks'].mean()) # 85.0
print(df[df['Marks'] > 80]) # filtered rows
4.1 Reading and Filtering a CSV
import pandas as pd
df = pd.read_csv('students.csv')
threshold = 75
result = df[df['Marks'] > threshold]
print(result)
pd.read_csv(filename)returns a DataFrame; the first line becomes column headings.- Boolean indexing
df[condition]keeps only rows where the condition isTrue. df['Marks'].mean()computes the average of one column;df.mean(numeric_only=True)averages all numeric columns.
import pandas as pd
df = pd.read_csv('students.csv')
subjects = ['Math', 'Science', 'English']
df['Average'] = df[subjects].mean(axis=1) # row-wise average per student
print(df[['Name', 'Average']])
Pandas Examiner Tip: Write the column name exactly as it appears in the question (Marks, not marks). Show the filter expression on its own line; examiners look for df[df[column] > threshold] as the decisive step.
After-Topic PYQs:
- 2025-26 (Sec C, 7 Marks): "Explain the concept of DataFrame in pandas. Write a Python program to create a DataFrame from a dictionary and print it."
- 2024-25 (Sec C, 7 Marks): "Write a program to read a CSV file and display the rows where a specific column value exceeds a given threshold."
- 2024-25 (Sec C, 7 Marks): "Write a program to read data from a CSV file 'students.csv', calculate the average marks for each student, and display the results."
- 2023-24 (Sec A, 2 Marks): "Describe about different functions of matplotlib and pandas."
5. Tkinter Introduction and Widgets
Tkinter: Python's standard GUI (Graphical User Interface) library, built on the Tk toolkit. A program creates a root window, places widgets inside it, and calls mainloop() so the application waits for user events.
5.1 Minimal Window with a Label
from tkinter import Tk, Label
root = Tk()
root.title('My First GUI')
root.geometry('300x120')
label = Label(root, text='Hello from Tkinter!', font=('Arial', 14))
label.pack(pady=20)
root.mainloop()
5.2 Common Tk Widgets
| Widget | Class | Used for |
|---|---|---|
| Label | Label(root, text='...') |
display static text/image |
| Button | Button(root, text='Click', command=func) |
trigger an action |
| Entry | Entry(root, width=20) |
single-line text input |
| Text | Text(root, height=5, width=30) |
multi-line text input |
| Frame | Frame(root) |
group other widgets |
| Checkbutton | Checkbutton(root, text='Option') |
on/off choice |
| Radiobutton | Radiobutton(root, text='Male', value=1) |
one-of-many choice |
| Listbox | Listbox(root) |
select from a list |
| Scale | Scale(root, from_=0, to=100) |
slider input |
| Message | Message(root, text='...') |
wrapped multi-line label |
| Menu | Menu(root) |
menu bar |
5.3 Geometry Managers
pack()— places widgets in blocks, simplest for stacked layouts; optionsside,fill,padx,pady.grid(row=r, column=c)— table-like rows and columns; best for forms and calculators.place(x=..., y=...)— fixed pixel coordinates; rarely used for full applications.
Never mix pack() and grid() inside the same parent container.
5.4 Event Handling
from tkinter import Tk, Button, Label
root = Tk()
def on_click(event):
status.config(text='Button clicked at row ' + str(event.y // 30))
status = Label(root, text='Waiting...')
status.pack()
btn = Button(root, text='Click me')
btn.pack()
btn.bind('<Button-1>', on_click) # left mouse button
root.mainloop()
command=functionis used for a plain button click with no event details.widget.bind('<event>', handler)passes an event object containing data such asx,y,keysym,char.- Common events:
<Button-1>(left click),<KeyPress>,<Return>,<Double-Button-1>,<Motion>.
Tkinter Examiner Tip: For every GUI program, write these four markers explicitly: root = Tk(), widget creation, a geometry manager (pack or grid), and root.mainloop(). Missing mainloop() means the window closes instantly and costs a mark.
After-Topic PYQs:
- 2025-26 (Sec A, 2 Marks): "What are Tkinter widgets?"
- 2025-26 (Sec C, 7 Marks): "Discuss Tkinter widgets. Write a program to create a simple window with a label using Tkinter."
- 2024-25 (Sec C, 7 Marks): "Discuss the role of event handling in Tkinter. How can you bind events to widgets? Provide examples."
- 2025-26 (Sec C, 7 Marks): "What is Tkinter? Explain the role of Tkinter in GUI programming using Python."
- 2024-25 (Sec C, 7 Marks): "What is GUI programming in Python? Write a GUI-based Python program using Tkinter to accept and display student data."
- 2023-24 (Sec C, 7 Marks): "Design a calculator with the following buttons and functionalities like addition, subtraction, multiplication, division and clear."
6. Tkinter Examples: Student Form and Calculator
6.1 Student Data Form
from tkinter import Tk, Label, Entry, Button, StringVar
root = Tk()
root.title('Student Data')
root.geometry('350x180')
name_var = StringVar()
roll_var = StringVar()
result = StringVar()
Label(root, text='Name').grid(row=0, column=0, padx=8, pady=6)
Entry(root, textvariable=name_var).grid(row=0, column=1)
Label(root, text='Roll No').grid(row=1, column=0, padx=8, pady=6)
Entry(root, textvariable=roll_var).grid(row=1, column=1)
def show():
result.set('Name: ' + name_var.get() + ' | Roll: ' + roll_var.get())
Button(root, text='Display', command=show).grid(row=2, column=0, pady=10)
Button(root, text='Clear', command=lambda: (name_var.set(''),
roll_var.set(''),
result.set(''))).grid(row=2, column=1)
Label(root, textvariable=result).grid(row=3, column=0, columnspan=2)
root.mainloop()
StringVar() holds text that updates the widget automatically; .get() reads the Entry and .set() writes to a Label.
6.2 Four-Function Calculator Skeleton
from tkinter import Tk, Entry, Button, StringVar
root = Tk()
root.title('Calculator')
display = StringVar()
Entry(root, textvariable=display, width=20, justify='right').grid(row=0, column=0, columnspan=4)
def press(key):
display.set(display.get() + key)
def calculate():
try:
display.set(str(eval(display.get()))) # simple exam demo
except ZeroDivisionError:
display.set('Cannot divide by zero')
except Exception:
display.set('Error')
def clear():
display.set('')
keys = [
('7',1,0), ('8',1,1), ('9',1,2), ('/',1,3),
('4',2,0), ('5',2,1), ('6',2,2), ('*',2,3),
('1',3,0), ('2',3,1), ('3',3,2), ('-',3,3),
('0',4,0), ('.',4,1), ('=',4,2), ('+',4,3),
]
for text, r, c in keys:
if text == '=':
Button(root, text=text, width=5, command=calculate).grid(row=r, column=c)
else:
Button(root, text=text, width=5,
command=lambda t=text: press(t)).grid(row=r, column=c)
Button(root, text='Clear', width=20, command=clear).grid(row=5, column=0, columnspan=4)
root.mainloop()
Important lambda note: command=lambda t=text: press(t) captures the current button text. Writing lambda: press(text) directly would make every button insert the last value of text.
Calculator Examiner Tip: The safest design uses grid(), a StringVar display, one press() function, one calculate() function and one clear() function. Handle division by zero separately; this avoids a runtime crash during demonstration.
Solved Exam-Ready Questions
Solved Q1 (2025-26 Sec C — 7 Marks | Survival Mode)
Q: How is Matplotlib used in Python? Write a program to plot a simple line graph.
Solution:
- Import:
import matplotlib.pyplot as pltloads the state-based plotting interface. - Prepare data: create two equal-length sequences
xandy. - Draw: call
plt.plot(x, y, marker='o'). - Annotate: add
title,xlabel,ylabel,legend()andgrid(True). - Display: call
plt.show().
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
plt.plot(x, y, marker='o', color='green', label='Observation')
plt.title('Simple Line Graph')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
The figure has five points joined by straight segments; the markers make each data value visible.
Solved Q2 (2024-25 Sec C — 7 Marks)
Q: Create a pie chart using matplotlib to represent the following data: Languages: Python, Java, C++, JavaScript, Ruby; Popularity: 30, 25, 20, 15, 10.
Solution:
- Total popularity , so slice angles are and the corresponding degrees are .
- Code:
import matplotlib.pyplot as plt
languages = ['Python', 'Java', 'C++', 'JavaScript', 'Ruby']
popularity = [30, 25, 20, 15, 10]
plt.pie(popularity, labels=languages, autopct='%1.1f%%', startangle=90)
plt.title('Language Popularity')
plt.axis('equal')
plt.show()
autopctprints the percentage computed from each value divided by the total;axis('equal')prevents an oval shape.
Solved Q3 (2024-25 Sec C — 7 Marks)
Q: Write a Python program using numpy to perform matrix operations.
Solution:
import numpy as np
A = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 10]])
B = np.array([[2, 0, 1],
[1, 3, 2],
[0, 1, 1]])
print("A + B =\n", A + B)
print("A - B =\n", A - B)
print("A * B (element-wise) =\n", A * B)
print("A @ B (matrix product) =\n", A @ B)
print("Transpose of A =\n", A.T)
print("Determinant =", np.linalg.det(A))
print("Inverse =\n", np.linalg.inv(A))
- Addition and subtraction are element-wise.
A * Bmultiplies matching positions;A @ Bperforms true matrix multiplication (row × column). - Determinant check: , nonzero, hence the inverse exists.
np.linalg.inv(A) @ Areturns the identity matrix, which verifies the result.
Solved Q4 (2023-24 Sec C — 7 Marks)
Q: Describe how to generate random numbers using NumPy. Write a Python program to create an array of random integers between and .
Solution:
- Concept: NumPy's random module uses a pseudorandom generator;
randint(low, high, size)returns integers fromlowinclusive tohighexclusive. - Program:
import numpy as np
arr = np.random.randint(10, 51, size=5)
print("Five random integers:", arr)
- Sample output:
[42 17 35 10 49]— numbers vary between runs because the seed is not fixed. - Range explanation: upper bound 51 is given because 50 must be included. With
randint(10, 50, 5)the largest possible value is 49. - Reproducibility:
np.random.seed(1)before generation fixes the sequence for testing.
Solved Q5 (2025-26 Sec C — 7 Marks)
Q: Explain the concept of DataFrame in pandas. Write a Python program to create a DataFrame from a dictionary and print it.
Solution:
- A DataFrame is a two-dimensional, size-mutable, labelled data structure. Each dictionary key becomes a column; each list element at position i forms row i.
import pandas as pd
data = {
'Roll': [21, 22, 23],
'Name': ['Asha', 'Ravi', 'Meera'],
'Marks': [88, 72, 95]
}
df = pd.DataFrame(data)
print(df)
- Output shape:
Roll Name Marks
0 21 Asha 88
1 22 Ravi 72
2 23 Meera 95
- Useful follow-ups:
df.shape → (3,3),df['Marks'].mean() → 85.0,df.head(2)prints the first two rows.
Solved Q6 (2024-25 Sec C — 7 Marks)
Q: Write a program to read a CSV file and display the rows where a specific column value exceeds a given threshold.
Solution:
import pandas as pd
df = pd.read_csv('students.csv')
column = 'Marks'
threshold = 75
filtered = df[df[column] > threshold]
print("Students with", column, "greater than", threshold)
print(filtered)
Steps: read_csv loads the table → df[column] extracts the chosen Series → > threshold creates a Boolean Series → df[boolean_series] keeps matching rows → print displays them. If the CSV has no header, use pd.read_csv('students.csv', header=None, names=['Roll','Name','Marks']).
Solved Q7 (2024-25 Sec C — 7 Marks)
Q: Write a program to read data from a CSV file 'students.csv', calculate the average marks for each student, and display the results.
Solution:
import pandas as pd
df = pd.read_csv('students.csv')
subjects = ['Math', 'Science', 'English']
df['Average'] = df[subjects].mean(axis=1)
print(df[['Name', 'Average']])
axis=1means the mean is calculated across columns for each row (one student).axis=0would give the class average per subject.- Example: marks
80, 90, 70give(80+90+70)/3 = 80.0. - Display only the required columns with double brackets
df[['Name','Average']]; single brackets would return a Series and raise aKeyErrorfor two names.
Solved Q8 (2025-26 Sec C — 7 Marks)
Q: Discuss Tkinter widgets. Write a program to create a simple window with a label using Tkinter.
Solution:
- Widgets: reusable GUI controls — Label (text), Button (action), Entry (input), Text (multi-line input), Frame (container), Checkbutton, Radiobutton, Listbox, Scale, Menu.
- Program:
from tkinter import Tk, Label
root = Tk()
root.title('Simple Window')
root.geometry('320x100')
lbl = Label(root, text='Welcome to Tkinter', font=('Arial', 14), fg='navy')
lbl.pack(pady=25)
root.mainloop()
- Line-by-line:
Tk()creates the top-level window;titleandgeometryset caption and size;Labeldisplays text;pack()registers it with the geometry manager;mainloop()starts the event loop. - Observation: without
mainloop()the script ends immediately and no window is seen.
Solved Q9 (2024-25 Sec C — 7 Marks)
Q: Discuss the role of event handling in Tkinter. How can you bind events to widgets? Provide examples.
Solution:
- Role: GUI programs are event-driven. The main loop waits for events (mouse click, key press, window resize) and calls the handler registered for that event.
- Two methods:
command=on a Button — no event object is passed.bind('<event>', handler)— the handler receives an event object with details.
from tkinter import Tk, Button, Label, Entry
root = Tk()
def show_key(event):
out.set('You pressed: ' + event.keysym)
def show_click():
out.set('Button pressed with command=')
out = None
lbl = Label(root, text='Press a key here'); lbl.pack()
lbl.bind('<KeyPress>', show_key)
lbl.focus_set() # keyboard events require focus
Entry(root, textvariable=None).pack()
Button(root, text='Click', command=show_click).pack()
out = __import__('tkinter').StringVar(value='Waiting...')
Label(root, textvariable=out).pack()
root.mainloop()
- Cleaner version: import
StringVardirectly and create it before the handlers. Events used commonly:<Button-1>,<KeyPress>,<Return>,<Double-Button-1>.
Solved Q10 (2023-24 Sec C — 7 Marks)
Q: Design a calculator with the following buttons and functionalities like addition, subtraction, multiplication, division and clear.
Solution: Use the grid-based program from Section 6.2. Examiner-facing steps:
- Create
root = Tk()and aStringVarlinked to anEntrydisplay. press(key)appends the clicked digit/operator to the display.calculate()evaluates the expression and catchesZeroDivisionErrorand other errors.clear()sets the display to an empty string.- Place 16 buttons with
grid(row=r, column=c); uselambda t=text: press(t)so each button remembers its own character. - Call
root.mainloop(). The essential logic isdisplay.set(str(eval(display.get()))), but a safer production version parses two operands and a single operator instead of usingeval.
Solved Q11 (2025-26 Sec A — 2 Marks)
Q: What is an IDE in Python programming?
Solution: An Integrated Development Environment is software that combines a code editor, interpreter/console, project/file browser and debugger in one window. Examples are IDLE (bundled with Python), PyCharm, VS Code and Spyder. It increases productivity by allowing edit–run–debug without switching applications.
Solved Q12 (2023-24 Sec A — 2 Marks)
Q: Describe the difference between linspace and argspace.
Solution: The intended NumPy function is arange (the PYQ prints "argspace"). np.linspace(start, stop, num) returns exactly num equally spaced values and includes stop by default; np.arange(start, stop, step) uses a fixed step and excludes stop, so the number of elements depends on the step. Example: np.linspace(0,1,5) → [0.,0.25,0.5,0.75,1.] while np.arange(0,1,0.25) → [0.,0.25,0.5,0.75].
Practice Questions (Self-Test)
- (2 Marks) Give one use each of
np.eye(),np.linspace()andnp.random.randint(). - (2 Marks) Name the Tk geometry manager suitable for a calculator keypad. (Ans:
grid()) - (7 Marks) Plot
y = x^2forx = range(-5,6)using Matplotlib with markers, title and grid. - (7 Marks) Create a 3×3 NumPy matrix, print its transpose, determinant and inverse.
- (7 Marks) Read
marks.csv, add aGradecolumn (>=80→ A,>=60→ B, else C) and print the DataFrame. - (7 Marks) Build a Tkinter window with an Entry and a Button that displays the entered text in a Label using
StringVar. - (7 Marks) Explain with code how
widget.bind('<Return>', handler)differs fromButton(command=handler).