0% found this document useful (0 votes)
5 views32 pages

Python Exam Notes

The document provides comprehensive notes for Python programming exam preparation, covering essential topics such as modules, dictionaries, sets, lists, tuples, and data visualization. Each topic includes definitions, key features, syntax, operations, and real-world applications, along with exam tips. The notes aim to enhance understanding and practical coding skills in Python.

Uploaded by

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

Python Exam Notes

The document provides comprehensive notes for Python programming exam preparation, covering essential topics such as modules, dictionaries, sets, lists, tuples, and data visualization. Each topic includes definitions, key features, syntax, operations, and real-world applications, along with exam tips. The notes aim to enhance understanding and practical coding skills in Python.

Uploaded by

qassimm085
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

University Exam Preparation Notes


Complete Theory + Code + Exam Tips

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

# Method 2: Import specific function


from math import sqrt, pi
print(sqrt(25)) # Output: 5.0

# Method 3: Import with alias


import numpy as np
arr = [Link]([1, 2, 3])

# Method 4: Import everything (not recommended)


from math import *
print(cos(0)) # Output: 1.0

5. Creating a User-Defined Module


Step 1 — Create [Link]:
# [Link]
def greet(name):
return f'Hello, {name}!'
PI = 3.14159
Step 2 — Import and use it:
import mymodule
print([Link]('Alice')) # Output: Hello, Alice!
print([Link]) # Output: 3.14159

6. The __name__ Variable


Every module has a built-in __name__ variable. When the module is run directly, __name__ equals
'__main__'. When imported, it equals the module's filename.
# [Link]
def add(a, b):
return a + b

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.

3. Syntax and Basic Operations


# Creating a dictionary
student = {'name': 'Alice', 'age': 21, 'grade': 'A'}

# 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

for key, val in [Link]():


print(key, val)

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

6. Default Dictionary ([Link])


A defaultdict never raises a KeyError. It automatically creates a default value for missing keys using a
factory function (int, list, str, etc.).
from collections import defaultdict

# Default value: 0 (int)


marks = defaultdict(int)
marks['Alice'] += 10
marks['Bob'] += 20
print(marks['Charlie']) # Output: 0 (not KeyError!)

# Default value: empty list


groups = defaultdict(list)
groups['A'].append('Alice')
groups['A'].append('Bob')
groups['B'].append('Charlie')
print(groups)
# Output: defaultdict(<class 'list'>, {'A': ['Alice', 'Bob'], 'B': ['Charlie']})

7. OrderedDict vs defaultdict vs Regular Dict


Feature dict OrderedDict defaultdict
Order preserved Yes (3.7+) Yes (always) Yes (3.7+)
KeyError on missing Yes Yes No — returns default
key
Feature dict OrderedDict defaultdict
Default value support No No Yes
move_to_end() No Yes No
Use case General Order-sensitive Counting/Grouping
purpose

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

3. Syntax and Operations


# Creating a set
fruits = {'apple', 'banana', 'cherry', 'apple'}
print(fruits) # Output: {'banana', 'cherry', 'apple'} (no duplicates)

# Empty set — must use set(), NOT {}


empty = set() # {} creates an empty DICTIONARY

# Add and remove


[Link]('mango')
[Link]('banana') # Raises KeyError if not found
[Link]('kiwi') # No error if not found

# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b) # Union: {1, 2, 3, 4, 5, 6}


print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric Diff: {1, 2, 5, 6}

# Membership test (very fast)


print(3 in a) # Output: True

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.

3. Syntax and Operations


# Creating a list
marks = [85, 92, 78, 95, 88]
mixed = [1, 'hello', 3.14, True]

# 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]

4. Nested List (2D List)


matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2]) # Output: 6

# Print all elements


for row in matrix:
for val in row:
print(val, end=' ')
print()

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

3. Syntax and Operations


# Creating tuples
coords = (10, 20, 30)
single = (42,) # Single element — note the comma!
nested = ((1, 2), (3, 4))

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

4. List vs Tuple — Comparison Table


Feature List Tuple
Syntax [] ()
Mutability Mutable Immutable
Speed Slower Faster
Feature List Tuple
Memory More Less
Methods More (append, remove, sort, etc.) Only count() and index()
Used as dict key No Yes
Use case Dynamic data Fixed/constant data

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

x = [2019, 2020, 2021, 2022, 2023]


y = [50, 70, 65, 90, 110]

[Link](x, y, marker='o', color='blue', label='Sales')


[Link]('Yearly Sales Trend')
[Link]('Year')
[Link]('Sales (in thousands)')
[Link]()
[Link](True)
[Link]()

Bar Chart
subjects = ['Math', 'English', 'Science', 'History']
marks = [85, 72, 90, 68]

[Link](subjects, marks, color=['red', 'green', 'blue', 'orange'])


[Link]('Subject-wise Marks')
[Link]('Subjects')
[Link]('Marks')
[Link]()
Scatter Plot
hours = [2, 3, 5, 7, 8, 9]
scores = [50, 60, 72, 85, 88, 95]

[Link](hours, scores, color='purple', s=100)


[Link]('Study Hours vs Exam Score')
[Link]('Hours Studied')
[Link]('Score')
[Link]()

Histogram
import random
data = [[Link](60, 10) for _ in range(200)]

[Link](data, bins=20, color='teal', edgecolor='black')


[Link]('Score Distribution')
[Link]('Scores')
[Link]('Frequency')
[Link]()

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.

2. Key Components of an IDE


• Code Editor — syntax highlighting, auto-complete, code formatting.
• Debugger — set breakpoints, inspect variables, step through code.
• Compiler / Interpreter — run code directly from the IDE.
• Version Control Integration — built-in Git support.
• Project Manager — organize files and directories.
• Terminal / Console — run shell commands without leaving the IDE.

3. Popular Python IDEs


IDE Best For Key Feature
PyCharm Professional Python Smart code completion, Django support
development
VS Code Lightweight, all-purpose Extensions, Git integration
Jupyter Notebook Data science, ML Interactive cell-based execution
IDLE Beginners Ships with Python installation
Spyder Scientific computing Variable explorer, Matplotlib integration
Google Colab Cloud-based ML/AI Free GPU, sharable notebooks

4. Advantages of Using an IDE


• Increased Productivity — auto-complete and code suggestions reduce typing time.
• Error Detection — real-time syntax checking highlights errors before running.
• Debugging Made Easy — step-by-step debugging with breakpoints.
• Code Navigation — jump to definitions, references, and usages instantly.
• Refactoring Support — rename variables, extract methods across the project.
• Integrated Testing — run unit tests directly within the IDE.

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.

2. File Opening Modes


Mode Description
'r' Read only (default). File must exist.
'w' Write only. Creates new file or truncates existing.
'a' Append. Adds content at end without deleting existing data.
'x' Exclusive creation. Fails if file already exists.
'r+' Read and Write. File must exist.
'rb' Read in binary mode.
'wb' Write in binary mode.

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

print('File written successfully.')


File written successfully.

4. Reading from a File


# Read entire file
with open('[Link]', 'r') as f:
content = [Link]()
print(content)

# Read line by line


with open('[Link]', 'r') as f:
for line in f:
print([Link]())

# Read all lines as a list


with open('[Link]', 'r') as f:
lines = [Link]()
print(lines)
Hello, World!
Python File Handling
5. Appending to a File
with open('[Link]', 'a') as f:
[Link]('New line appended.\n')

6. File Handling with Exception Handling


try:
with open('[Link]', 'r') as f:
print([Link]())
except FileNotFoundError:
print('Error: File does not exist.')
except PermissionError:
print('Error: No permission to access file.')
finally:
print('File operation attempted.')
Error: File does not exist.
File operation attempted.

7. Working with CSV Files


import csv

# 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.

3. Basic Method Overriding Example


class Animal:
def speak(self):
return 'Some generic sound'

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

print([Link]()) # Output: Some generic sound


print([Link]()) # Output: Woof!
print([Link]()) # Output: Meow!

4. Using super() to Call Parent Method


class Vehicle:
def info(self):
return 'This is a vehicle.'

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.

5. Method Overriding in Multilevel Inheritance


class Shape:
def area(self):
return 0

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

6. Method Overriding vs Method Overloading


Feature Overriding Overloading
Definition Redefining parent method in child Same method, different parameters
Inheritance Required Not required
Runtime/Compile Runtime (dynamic) Compile time (static)
Python support Fully supported Not natively supported (use *args)
Purpose Change behavior for subclass Handle multiple argument types

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.

2. Complete Comparison Table


Feature List Tuple Set Dictionary
Syntax [] () {} { key: value }
Ordered Yes Yes No Yes (3.7+)
Mutable Yes No Yes Yes
Duplicates Allowed Allowed Not allowed Keys: No, Values:
Yes
Indexing Yes Yes No By key
Speed Moderate Fast Very fast Fast (hash-based)
(sets)
Nesting Yes Yes No (immutable Yes
items)
Use case General Fixed data Unique items Key-value mapping
sequence
Dict key usage No Yes No N/A

3. When to Use Which


• List: When you need ordered, changeable data — e.g., student marks, shopping cart.
• Tuple: When data must not be changed — e.g., GPS coordinates, RGB values.
• Set: When you need unique elements and fast membership testing — e.g., removing duplicates.
• Dictionary: When you need to map keys to values — e.g., student records, JSON data.

4. Stack and Queue Using Lists


Stack (LIFO — Last In First Out)
stack = []
[Link](10) # Push
[Link](20)
[Link](30)
print([Link]()) # Pop → Output: 30
print(stack) # Output: [10, 20]

Queue (FIFO — First In First Out)


from collections import deque
queue = deque()
[Link]('Alice') # Enqueue
[Link]('Bob')
[Link]('Charlie')
print([Link]()) # Dequeue → Output: Alice
print(queue) # Output: deque(['Bob', 'Charlie'])

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.

2. Basic Tkinter Structure


import tkinter as tk

root = [Link]() # Create main window


[Link]('My Application') # Set window title
[Link]('400x300') # Set window size (width x height)

# Add widgets here

[Link]() # Start the event loop

3. Complete GUI with Entry Box, Combo Box, Menu, and Check Button
import tkinter as tk
from tkinter import ttk, messagebox

# ─── Main Window ────────────────────────────────────────────


root = [Link]()
[Link]('Student Registration Form')
[Link]('450x400')
[Link](bg='#f0f0f0')

# ─── Menu Bar ───────────────────────────────────────────────


menu_bar = [Link](root)

file_menu = [Link](menu_bar, tearoff=0)


file_menu.add_command(label='New', command=lambda: print('New clicked'))
file_menu.add_command(label='Open', command=lambda: print('Open clicked'))
file_menu.add_separator()
file_menu.add_command(label='Exit', command=[Link])
menu_bar.add_cascade(label='File', menu=file_menu)

help_menu = [Link](menu_bar, tearoff=0)


help_menu.add_command(label='About', command=lambda: [Link]('About',
'v1.0'))
menu_bar.add_cascade(label='Help', menu=help_menu)

[Link](menu=menu_bar)

# ─── Entry Box (Name Input) ──────────────────────────────────


[Link](root, text='Name:', bg='#f0f0f0', font=('Arial', 11)).grid(
row=0, column=0, padx=10, pady=10, sticky='w')
name_var = [Link]()
name_entry = [Link](root, textvariable=name_var, font=('Arial', 11), width=25)
name_entry.grid(row=0, column=1, padx=10, pady=10)

# ─── Combo Box (Department) ──────────────────────────────────


[Link](root, text='Department:', bg='#f0f0f0', font=('Arial', 11)).grid(
row=1, column=0, padx=10, pady=10, sticky='w')

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

# ─── Check Buttons ───────────────────────────────────────────


[Link](root, text='Subjects:', bg='#f0f0f0', font=('Arial', 11)).grid(
row=2, column=0, padx=10, pady=10, sticky='w')

python_var = [Link]()
java_var = [Link]()
ml_var = [Link]()

[Link](root, text='Python', variable=python_var, bg='#f0f0f0',


font=('Arial', 10)).grid(row=2, column=1, sticky='w', padx=10)
[Link](root, text='Java', variable=java_var, bg='#f0f0f0',
font=('Arial', 10)).grid(row=3, column=1, sticky='w', padx=10)
[Link](root, text='Machine Learning', variable=ml_var, bg='#f0f0f0',
font=('Arial', 10)).grid(row=4, column=1, sticky='w', padx=10)

# ─── Submit Button ───────────────────────────────────────────


def submit():
name = name_var.get()
dept = dept_var.get()
subjects = []
if python_var.get(): [Link]('Python')
if java_var.get(): [Link]('Java')
if ml_var.get(): [Link]('Machine Learning')

if not name:
[Link]('Warning', 'Please enter your name!')
return

info = f'Name: {name}\nDept: {dept}\nSubjects: {', '.join(subjects)}'


[Link]('Registration Details', info)

[Link](root, text='Submit', command=submit, font=('Arial', 11),


bg='#2E75B6', fg='white', width=15).grid(row=5, column=1, pady=20)

[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

students = [] # Global list of student dictionaries

# ─── 1. Add Record ───────────────────────────────────────────


def add_student():
roll = input('Enter Roll Number : ')
name = input('Enter Name : ')
marks = float(input('Enter Marks : '))
course = input('Enter Course : ')

student = {'roll': roll, 'name': name, 'marks': marks, 'course': course}


[Link](student)
print(f'\n Record added for {name}.\n')

# ─── 2. Remove Record ────────────────────────────────────────


def remove_student():
roll = input('Enter Roll Number to remove: ')
for s in students:
if s['roll'] == roll:
[Link](s)
print(f' Record with Roll {roll} removed.\n')
return
print(' Record not found.\n')

# ─── 3. Search Record ────────────────────────────────────────


def search_student():
roll = input('Enter Roll Number to search: ')
for s in students:
if s['roll'] == roll:
print('\n --- Student Found ---')
for key, val in [Link]():
print(f' {[Link]():8}: {val}')
print()
return
print(' Student not found.\n')

# ─── 4. Sort Records ─────────────────────────────────────────


def sort_students():
key = input('Sort by (name / marks): ').strip().lower()
if key in ('name', 'marks'):
[Link](key=lambda s: s[key])
print(f' Records sorted by {key}.\n')
else:
print(' Invalid sort key.\n')

# ─── 5. Display All Records ──────────────────────────────────


def display_students():
if not students:
print(' No records found.\n')
return
print()
print(f' {'Roll':<8} {'Name':<20} {'Marks':<8} {'Course'}')
print(' ' + '-' * 50)
for s in students:
print(f" {s['roll']:<8} {s['name']:<20} {s['marks']:<8} {s['course']}")
print()

# ─── Main Menu ───────────────────────────────────────────────


def main():
while True:
print('===== Student Management System =====')
print(' 1. Add Student')
print(' 2. Remove Student')
print(' 3. Search Student')
print(' 4. Sort Students')
print(' 5. Display All Students')
print(' 6. Exit')
choice = input('\nEnter your choice (1-6): ')

if choice == '1': add_student()


elif choice == '2': remove_student()
elif choice == '3': search_student()
elif choice == '4': sort_students()
elif choice == '5': display_students()
elif choice == '6': print('Exiting...'); break
else: print('Invalid choice. Try again.\n')

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

Enter your choice (1-6): 5

Roll Name Marks Course


--------------------------------------------------
101 Alice 92.0 CS
102 Bob 78.5 IT
103 Charlie 85.0 CS

4. Key Concepts Used


• List of dictionaries — each student is a dict, all students in a list.
• lambda function — used in sort() as key=lambda s: s['name'].
• String formatting with f-strings — clean tabular output.
• Function-based design — each operation is a separate function.

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

Example — Find the first negative number:


numbers = [10, 25, 7, -3, 14, -8]

for num in numbers:


if num < 0:
print(f'First negative number found: {num}')
break # Exit the loop immediately
print(f'Positive: {num}')
Positive: 10
Positive: 25
Positive: 7
First negative number found: -3

3. continue Statement
Syntax:
continue

Example — Print only even numbers:


for i in range(1, 11):
if i % 2 != 0:
continue # Skip odd numbers
print(i, end=' ')
2 4 6 8 10

4. break in While Loop


# Password checker
password = 'python123'

while True:
attempt = input('Enter password: ')
if attempt == password:
print('Access granted!')
break # Correct password — exit loop
print('Wrong password. Try again.')

5. continue in While Loop


# Print numbers 1-10, skip multiples of 3
i = 0
while i < 10:
i += 1
if i % 3 == 0:
continue # Skip 3, 6, 9
print(i, end=' ')
1 2 4 5 7 8 10

6. Nested Loop with break


# Find a specific element in a 2D matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5
found = False

for row in matrix:


for val in row:
if val == target:
print(f'Target {target} found!')
found = True
break # Only breaks inner loop
if found:
break # Breaks outer loop too
Target 5 found!

7. break vs continue — Comparison


Feature break continue
Effect Exits the loop entirely Skips current iteration only
Loop continues? No Yes
Use case Early exit when condition met Skip unwanted values
With nested loops Breaks only the inner loop Skips only current inner iteration
Example use Search and stop, exit on error Filter values, skip exceptions

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

You might also like