Python Exam Notes
Python Exam Notes
Topics Covered: Modules • Dictionaries • Sets • Lists • Tuples • Data Visualization • IDEs • File Handling • Method
Overriding • Data Structures • Tkinter • Management System • Break & Continue
TOPIC 1: MODULES IN PYTHON
1. Definition
A module is a file containing Python definitions, functions, classes, and variables, saved with a .py
extension. It allows code reusability and better organization of programs.
2. Key Features
• Promotes code reusability — write once, use anywhere.
• Supports namespace management — avoids naming conflicts.
• Python has built-in, standard library, and user-defined modules.
• Modules can be imported fully or partially.
3. Types of Modules
Type Description Example
Built-in Pre-installed with Python interpreter math, os, sys
Standard Library Come with Python installation datetime, random, json
Third-party Installed via pip numpy, pandas, flask
User-defined Created by the programmer [Link]
4. Import Syntax
# Method 1: Import full module
import math
print([Link](16)) # Output: 4.0
if __name__ == '__main__':
print(add(3, 4)) # Runs only when executed directly
7. Real-World Applications
• math module — scientific calculations (sqrt, log, sin, cos)
• os module — file and directory operations
• datetime module — date and time management in applications
• json module — parsing API data in web projects
• random module — generating OTPs, simulations, games
Exam Tip: Know all 4 import methods with syntax. Always mention __name__ == '__main__' in
answers about user-defined modules.
Important Point: The 'from module import *' method is discouraged in production code as it pollutes
the namespace.
TOPIC 2: DICTIONARY IN PYTHON
1. Definition
A dictionary is an unordered (Python < 3.7) / ordered (Python >= 3.7) collection of key-value pairs.
Keys must be unique and immutable; values can be of any type. Defined using curly braces {}.
2. Key Features
• Mutable — elements can be added, changed, or removed.
• Keys must be unique and immutable (strings, numbers, tuples).
• Values can be duplicated and of any type.
• Ordered by insertion order since Python 3.7.
• Dynamic sizing — grows as needed.
# Accessing values
print(student['name']) # Output: Alice
print([Link]('age')) # Output: 21
# Adding / Updating
student['city'] = 'Mumbai' # Add new key
student['age'] = 22 # Update existing key
# Deleting
del student['grade']
[Link]('city')
# Iterating
for key, value in [Link]():
print(key, '->', value)
# Dictionary methods
print([Link]()) # dict_keys(['name', 'age'])
print([Link]()) # dict_values(['Alice', 22])
print(len(student)) # 2
4. Dictionary Comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
5. Ordered Dictionary ([Link])
An OrderedDict remembers the insertion order of keys. Before Python 3.7, regular dicts were
unordered, so OrderedDict was essential for order-sensitive operations.
from collections import OrderedDict
od = OrderedDict()
od['banana'] = 3
od['apple'] = 1
od['cherry'] = 2
# Output:
# banana 3
# apple 1
# cherry 2
# Move to end
od.move_to_end('banana')
# Move to front
od.move_to_end('cherry', last=False)
8. Real-World Applications
• Student records system — roll number as key, details as value
• Word frequency counter using defaultdict(int)
• JSON data parsing from APIs (dictionaries map directly to JSON objects)
• Configuration files — settings stored as key-value pairs
• Caching (memoization) — function results stored by input as key
Exam Tip: Always specify the Python version when discussing dictionary ordering. For defaultdict,
clearly state what happens when a missing key is accessed.
Important Point: [Link](key, default) is safer than dict[key] because it never raises KeyError.
TOPIC 3: SET IN PYTHON
1. Definition
A set is an unordered, mutable collection of unique elements. Sets do not allow duplicate values and do
not support indexing or slicing. Defined using curly braces {} or set() constructor.
2. Key Features
• No duplicate elements — automatically removes duplicates.
• Unordered — insertion order is not preserved.
• Mutable — elements can be added/removed (but elements must be immutable).
• Supports mathematical set operations (union, intersection, difference).
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
4. Frozenset
A frozenset is an immutable version of a set. Once created, elements cannot be added or removed. It
can be used as a dictionary key.
fs = frozenset([1, 2, 3, 4])
print(fs) # Output: frozenset({1, 2, 3, 4})
# [Link](5) # AttributeError — immutable!
5. Real-World Applications
• Removing duplicate entries from a list of emails or usernames.
• Finding common elements between two datasets (intersection).
• Membership testing — checking if a value exists in a large collection.
• Tag systems in blogs — storing unique tags per post.
Exam Tip: Remember: empty set = set(), NOT {}. Frozenset is the immutable counterpart of set. Sets
support mathematical operations using operators (|, &, -, ^) or methods (union(), intersection()).
TOPIC 4: LIST IN PYTHON
1. Definition
A list is an ordered, mutable collection that can store elements of different data types. Lists support
duplicate values and are defined using square brackets [].
2. Key Features
• Ordered — elements maintain their insertion order.
• Mutable — elements can be changed, added, or removed.
• Heterogeneous — can store integers, strings, floats, etc. together.
• Supports indexing (positive and negative) and slicing.
• Dynamic — size changes automatically.
# Indexing
print(marks[0]) # Output: 85 (first element)
print(marks[-1]) # Output: 88 (last element)
# Slicing
print(marks[1:4]) # Output: [92, 78, 95]
print(marks[::-1]) # Output: [88, 95, 78, 92, 85] (reversed)
# Common methods
[Link](90) # Add at end
[Link](2, 100) # Insert at index 2
[Link](78) # Remove first occurrence of 78
[Link]() # Remove and return last element
[Link]() # Sort in ascending order
[Link]() # Reverse the list
print([Link](85)) # Count occurrences
print([Link](92)) # Find index
# List comprehension
squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
5. Real-World Applications
• Shopping cart — storing selected items.
• Student mark sheets — storing and sorting marks.
• Task management — to-do lists with add/remove functionality.
• Image processing — pixel values stored in nested lists.
Exam Tip: Know the difference between append() (adds one item) and extend() (adds all items of an
iterable). Also know sort() vs sorted() — sort() modifies in place, sorted() returns a new list.
TOPIC 5: TUPLE IN PYTHON
1. Definition
A tuple is an ordered, immutable collection of elements. Once created, elements cannot be changed,
added, or removed. Tuples are defined using parentheses ().
2. Key Features
• Immutable — cannot be modified after creation.
• Ordered — maintains insertion order.
• Allows duplicate values.
• Faster than lists due to immutability.
• Can be used as dictionary keys (unlike lists).
# Accessing elements
print(coords[0]) # Output: 10
print(coords[-1]) # Output: 30
print(coords[0:2]) # Output: (10, 20)
# Tuple unpacking
x, y, z = coords
print(x, y, z) # Output: 10 20 30
# Tuple methods
t = (1, 2, 2, 3, 4, 2)
print([Link](2)) # Output: 3
print([Link](3)) # Output: 3
# Concatenation
t1 = (1, 2, 3)
t2 = (4, 5, 6)
print(t1 + t2) # Output: (1, 2, 3, 4, 5, 6)
5. Real-World Applications
• Geographic coordinates — (latitude, longitude) stored as tuple.
• Database records — each row returned as a tuple (read-only).
• Function returning multiple values — Python returns them as a tuple.
• RGB color codes — (255, 0, 0) for red.
Exam Tip: A single-element tuple requires a trailing comma: (42,). Without it, Python treats it as just
parentheses around an integer. Tuples can be keys in dictionaries; lists cannot.
TOPIC 6: TYPES OF PLOTS IN DATA VISUALIZATION
1. Definition
Data visualization is the graphical representation of data to uncover patterns, trends, and insights.
Python's matplotlib and seaborn libraries are widely used for this purpose.
2. Types of Plots
Plot Type Best For Key Function
Line Plot Trends over time [Link]()
Bar Chart Comparing categories [Link]() / [Link]()
Histogram Frequency distribution [Link]()
Scatter Plot Correlation between two variables [Link]()
Pie Chart Proportions of a whole [Link]()
Box Plot Statistical spread & outliers [Link]()
Heatmap Matrix / correlation data [Link]()
Area Plot Cumulative trends plt.fill_between()
3. Code Examples
Line Plot
import [Link] as plt
Bar Chart
subjects = ['Math', 'English', 'Science', 'History']
marks = [85, 72, 90, 68]
Histogram
import random
data = [[Link](60, 10) for _ in range(200)]
4. Real-World Applications
• Business dashboards — sales, revenue, and KPI tracking.
• Scientific research — presenting experimental results.
• Machine learning — visualizing training loss, accuracy curves.
• Finance — stock price trends over time (line plot).
Exam Tip: For theory: define each chart type and state what data it is best suited for. For code:
always include [Link](), [Link](), [Link](), and [Link]().
TOPIC 7: IMPORTANCE OF IDEs
1. Definition
An IDE (Integrated Development Environment) is a software application that provides a comprehensive
set of tools for software development in a single interface. It combines a code editor, debugger,
compiler/interpreter, and other tools.
5. Real-World Applications
• PyCharm is used in professional web development with Django and Flask.
• Jupyter Notebook is the standard tool in data science and machine learning.
• VS Code is widely used for full-stack development (Python + JavaScript).
• Google Colab is used in academia for collaborative AI research.
Exam Tip: Be ready to compare at least 2-3 IDEs. Mention that Jupyter Notebook is cell-based and
ideal for data science, while PyCharm is better suited for large-scale application development.
TOPIC 8: FILE HANDLING IN PYTHON
1. Definition
File handling allows Python programs to read from and write to files stored on the disk. Python uses the
built-in open() function to work with files.
3. Writing to a File
# Write mode — creates or overwrites the file
with open('[Link]', 'w') as f:
[Link]('Hello, World!\n')
[Link]('Python File Handling\n')
# Writing CSV
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](['Name', 'Age', 'Grade'])
[Link](['Alice', 21, 'A'])
[Link](['Bob', 22, 'B'])
# Reading CSV
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row)
['Name', 'Age', 'Grade']
['Alice', '21', 'A']
['Bob', '22', 'B']
8. Real-World Applications
• Log files — recording application events and errors.
• CSV processing — reading/writing student or employee records.
• Configuration files — storing application settings.
• Data persistence — saving game state or user data.
Exam Tip: Always use 'with open()' instead of open() + close(). The 'with' statement automatically
closes the file, even if an exception occurs — this is called a context manager.
Important Point: Know the difference between read() (reads all as string), readline() (reads one
line), and readlines() (reads all lines as a list).
TOPIC 9: METHOD OVERRIDING IN PYTHON
1. Definition
Method overriding is an OOP feature where a child class provides its own implementation of a method
that is already defined in the parent class. The child class method has the same name and signature as
the parent method.
2. Key Features
• Achieves runtime polymorphism.
• The child class method replaces the parent class method.
• The parent method can still be accessed using super().
• Does not require any special decorator.
class Dog(Animal):
def speak(self): # Overrides [Link]()
return 'Woof!'
class Cat(Animal):
def speak(self): # Overrides [Link]()
return 'Meow!'
a = Animal()
d = Dog()
c = Cat()
class Car(Vehicle):
def info(self):
parent_info = super().info() # Call parent method
return parent_info + ' Specifically, a Car.'
c = Car()
print([Link]())
# Output: This is a vehicle. Specifically, a Car.
class Rectangle(Shape):
def __init__(self, l, w):
self.l = l
self.w = w
def area(self): # Overrides [Link]()
return self.l * self.w
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
def area(self): # Overrides [Link]()
return self.l ** 2
s = Square(5)
print([Link]()) # Output: 25
7. Real-World Applications
• Payment systems — base PaymentMethod class, override process() in CreditCard, UPI,
NetBanking.
• GUI frameworks — base Widget class, override draw() in Button, TextBox, Label.
• Game development — base Character class, override attack() for different character types.
Exam Tip: Always mention that Python supports method overriding but NOT native method
overloading. Use super() to extend parent behavior rather than completely replacing it.
TOPIC 10: DATA STRUCTURES IN PYTHON
1. Overview
Python has four built-in data structures: List, Tuple, Set, and Dictionary. Each serves a different
purpose and has unique properties.
5. Real-World Applications
• List — to-do apps, playlist management, shopping carts.
• Tuple — database records, function multiple return values.
• Set — finding common friends, removing duplicate data.
• Dictionary — JSON APIs, caching, configuration management.
• Stack — browser back button, undo/redo in text editors.
• Queue — print queue, CPU scheduling, BFS in graphs.
Exam Tip: For comparison questions, always present a table. Be specific: Sets use hash tables
internally (O(1) lookup), while Lists use sequential search (O(n)).
TOPIC 11: PYTHON PROGRAM USING TKINTER
1. Definition
Tkinter is Python's standard GUI (Graphical User Interface) library. It provides widgets to build desktop
applications. Tkinter is included in the Python standard library — no installation needed.
3. Complete GUI with Entry Box, Combo Box, Menu, and Check Button
import tkinter as tk
from tkinter import ttk, messagebox
[Link](menu=menu_bar)
dept_var = [Link]()
dept_combo = [Link](root, textvariable=dept_var, font=('Arial', 11),
values=['Computer Science', 'Mechanical', 'Electronics', 'Civil'], width=23)
dept_combo.grid(row=1, column=1, padx=10, pady=10)
dept_combo.set('Select Department')
python_var = [Link]()
java_var = [Link]()
ml_var = [Link]()
if not name:
[Link]('Warning', 'Please enter your name!')
return
[Link]()
4. Widget Summary Table
Widget Purpose Key Parameters
[Link] Single-line text input textvariable, width, font
[Link] Dropdown selection list values, textvariable
[Link] Application menu bar tearoff, add_command, add_cascade
[Link] Toggle on/off selection variable (BooleanVar), text
[Link] Clickable action button command, text, bg, fg
[Link] Display static text text, font, bg
Exam Tip: For layout: grid() is preferred over pack() in structured forms. Always use textvariable
(StringVar/BooleanVar) instead of accessing widget values directly. Combobox is from ttk, not tk.
TOPIC 12: STUDENT MANAGEMENT SYSTEM
1. Overview
A management system using Lists and Dictionaries to perform Add, Remove, Search, Sort, and Display
operations on student records.
2. Full Program
# Student Management System
# Each record is a dictionary; all records stored in a list
main()
3. Sample Output
===== Student Management System =====
1. Add Student
2. Remove Student
3. Search Student
4. Sort Students
5. Display All Students
6. Exit
Exam Tip: Examiners want to see proper use of list operations (append, remove, sort) AND
dictionary access. Use lambda for sorting — it is the Pythonic way.
TOPIC 13: BREAK AND CONTINUE STATEMENTS
1. Definition
Break and Continue are loop control statements in Python that alter the normal flow of loops.
• break: Terminates the loop immediately when the condition is met.
• continue: Skips the current iteration and moves to the next one.
2. break Statement
Syntax:
break
3. continue Statement
Syntax:
continue
while True:
attempt = input('Enter password: ')
if attempt == password:
print('Access granted!')
break # Correct password — exit loop
print('Wrong password. Try again.')
Exam Tip: In nested loops, break only exits the innermost loop. Use a flag variable (found = True) to
break out of multiple levels. Always give a practical example when explaining break and continue.
Important Point: Both break and continue work with for and while loops. The else clause of a loop
executes only if the loop was NOT terminated by break.
QUICK REVISION CHEATSHEET
Topic Key Points to Remember
Modules import / from-import / as / *import | __name__ == '__main__'
Dictionary Key-value pairs | .get() | .items() | OrderedDict | defaultdict
Set No duplicates | No index | |, &, -, ^ operations | frozenset
List Mutable | Ordered | append, insert, remove, sort, reverse
Tuple Immutable | single=(x,) | faster than list | dict key allowed
Visualization [Link]/bar/scatter/hist/pie | always add title & labels
IDEs PyCharm=professional | Jupyter=data science | VS Code=general
File Handling r/w/a/x modes | with open() | read/readline/readlines
Overriding Same method in child class | super() to call parent | polymorphism
Data Structures List=mutable | Tuple=immutable | Set=unique | Dict=key-value
Tkinter Entry/Combobox/Menu/Checkbutton | StringVar/BooleanVar | grid()
Mgmt System List of dicts | append/remove/sort | lambda for sort key
Break/Continue break=exit loop | continue=skip iteration | flag for nested break