PYTHON PROGRAMMING
Complete Exam Notes
Modules 1 – 4 | All Topics Covered
MODULE 1: Introduction to Python & Control Flow
1.1 What is Python?
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics,
created by Guido van Rossum (released 1991).
Key Features
• Interpreted – runs code line by line; easy to find errors
• Easy-to-use – uses English-like words and indentation (no curly braces)
• Dynamically typed – no need to declare variable types
• High-level – closer to human language; no memory management needed
• Object-oriented – treats everything as an object
Applications
• Web Development – Django, Flask frameworks
• Automation – file renaming, email sending, data download
• Data Science & ML – NumPy, Pandas, Matplotlib, TensorFlow
• Software Development – GUI apps (Tkinter, PyQt), games
• Software Testing – Unittest, Robot, PyUnit, CI/CD tools
1.2 Variables & Data Types
A variable is a named storage location for data. Syntax: variable_name = value
Rules for Variable Names:
• Must start with a letter or underscore
• Cannot start with a number
• Only alphanumeric characters and underscores
• Case-sensitive (age, Age, AGE are different)
• Cannot be a Python keyword
Python Data Types:
Category Type Example
Text str x = "Hello World"
Numeric int x = 20
Numeric float x = 20.5
Numeric complex x = 1j
Sequence list x = ["a", "b"]
Sequence tuple x = ("a", "b")
Sequence range x = range(6)
Mapping dict x = {"name": "Raj"}
Set set x = {"a", "b"}
Boolean bool x = True
None NoneType x = None
1.3 Tokens in Python
Tokens are the smallest units of a Python program. There are 5 types:
• Keywords – reserved words: if, else, for, while, def, class, True, False, None
• Identifiers – names for variables, functions, classes
• Literals – raw data values: string, numeric, boolean, special (None), collection
• Operators – symbols performing operations: +, -, *, /, ==, and, or, not
• Punctuators – structural symbols: (), [], {}, :, ,, ., ;
1.4 Python Operators
Arithmetic Operators:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x**y
// Floor Division x//y
Comparison Operators:
Operator Meaning
== Equal
!= Not equal
< Less than
> Greater than
<= Less or equal
>= Greater or equal
Logical Operators:
• and – True if both conditions are True
• or – True if at least one condition is True
• not – Reverses the result
Operator Precedence (High → Low):
Parentheses → ** → ~x → *, /, //, % → +, - → Bitwise → Relational → not → and → or
1.5 Type Conversion
Implicit Conversion – Python converts automatically (e.g., int + float → float)
Explicit Conversion – Manual using built-in functions:
• int() – converts to integer
• float() – converts to float
• str() – converts to string
• bool() – converts to boolean
1.6 Decision-Making Statements
if Statement
if condition:
statement(s)
if-else Statement
if condition:
statement(s)
else:
statement(s)
if-elif-else Statement
if condition1:
statement(s)
elif condition2:
statement(s)
else:
statement(s)
Nested if Statement
if condition1:
if condition2:
statement(s)
1.7 Loops
while Loop
• Executes block while condition is True
• Condition is checked before each iteration
while condition:
statement(s)
else: # runs when loop ends normally
statement(s)
for Loop
• Iterates over a sequence (list, tuple, string, range)
• Automatically ends when all items are processed
for variable in sequence:
statement(s)
else: # runs after all iterations
statement(s)
Control Statements:
• break – exits the loop immediately (skips else block)
• continue – skips current iteration
• pass – does nothing (placeholder)
1.8 Comments & Indentation
Single-line comment:
# This is a comment
Multi-line comment:
"""
This spans
multiple lines
"""
Indentation: Python uses whitespace (4 spaces) to define code blocks. Incorrect indentation causes
IndentationError.
MODULE 2: Functions & Modules
2.1 Functions
A function is a reusable block of code that performs a specific task.
def function_name(parameters):
"""docstring"""
statement(s)
return value
Types of Function Arguments
• Required (Positional) – must be passed in the correct order
• Keyword – passed with key=value; order doesn't matter
• Default – has a default value if not provided
• Variable-length (*args) – accepts any number of positional arguments
• Variable keyword (**kwargs) – accepts any number of keyword arguments
Example:
def greet(name, msg='Hello'): # name=required, msg=default
return f'{msg}, {name}!'
def add(*args): # variable-length
return sum(args)
def info(**kwargs): # keyword variable
for k, v in [Link]():
print(k, ':', v)
2.2 Scope and Lifetime
• Local scope – variable inside a function; exists only while function runs
• Global scope – variable outside all functions; accessible everywhere
• Use global keyword to modify a global variable inside a function
2.3 Types of Functions
Recursive Function
A function that calls itself. Must have a base case to stop.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
Anonymous (Lambda) Function
A small, unnamed function defined with lambda keyword.
square = lambda x: x * x
print(square(5)) # Output: 25
Functions with Multiple Return Values
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([3,1,4,1,5])
2.4 Modules
• A module is a file containing Python definitions and statements (.py file)
• Import: import math or from math import sqrt
• Built-in modules: math, os, random, sys, datetime
• User-defined: create [Link] and import it
Built-in Module Examples:
import math
print([Link](16)) # 4.0
print([Link]) # 3.14159...
import random
print([Link](1, 10))
MODULE 3: Data Structures in Python
3.1 Strings
A string is an immutable sequence of characters enclosed in quotes.
• Single/double quotes: 'hello', "hello"
• Triple quotes: '''multi-line''' used for multi-line strings
• Indexing starts from 0; negative indexing from -1 (end)
• Immutable – cannot be changed after creation
String Operations
Operation Syntax Result
Indexing s[0] First character
Slicing s[1:4] Characters 1 to 3
Concatenation s1 + s2 Joined string
Repetition s*3 String repeated 3 times
Membership 'a' in s True/False
Length len(s) Number of characters
Common String Methods
Method Description
[Link]() Convert to uppercase
[Link]() Convert to lowercase
[Link]() Remove leading/trailing spaces
[Link](a, b) Replace substring a with b
[Link]() Split into list of words
' '.join(lst) Join list into string
[Link](x) Index of first occurrence of x
len(s) Length of string
f-Strings (Formatted Strings)
name = "Alice"; age = 22
print(f"Name: {name}, Age: {age}")
3.2 Lists
A list is an ordered, mutable collection of elements using square brackets [].
• Can store mixed data types
• Supports duplicate values
• Indexing starts at 0; supports negative indexing
List Methods
Method Description
append(x) Add x to end
extend([x,y]) Add multiple elements
insert(i, x) Insert x at index i
remove(x) Remove first occurrence of x
pop(i) Remove element at index i (default: last)
sort() Sort in ascending order
reverse() Reverse the list
copy() Return a copy
clear() Remove all elements
index(x) Index of first x
count(x) Count occurrences of x
List Comprehension
A concise way to create lists:
squares = [x*x for x in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [x for x in range(1,11) if x%2==0] # [2, 4, 6, 8, 10]
3.3 Tuples
A tuple is an ordered, immutable collection using parentheses ().
• Cannot be changed after creation (no add/remove)
• Supports indexing, slicing, and traversal
• Single-element tuple requires a trailing comma: (5,)
Tuple Methods (only 2)
• count(x) – returns number of times x appears
• index(x) – returns index of first occurrence of x
Tuple Packing & Unpacking
t = 10, 20, 30 # Packing
a, b, c = t # Unpacking → a=10, b=20, c=30
3.4 Comparison: List vs Tuple vs Set vs Dict
Property List Tuple Set Dict
Brackets [] () {} { key:val }
Ordered Yes Yes No No (Py 3.7+: insertion)
Mutable Yes No Yes Yes
Duplicates Yes Yes No No (keys)
Indexing Yes Yes No By key
3.5 Dictionaries
A dictionary stores data as key–value pairs using curly braces {}.
• Keys must be unique and immutable (str, int, tuple)
• Values can be of any type
• Uses hashing internally → O(1) average access time
student = {"name": "Rahul", "age": 20}
print(student["name"]) # Rahul
print([Link]("grade")) # None (safe access)
Dictionary Methods
Method Description
[Link]() Return all keys
[Link]() Return all values
[Link]() Return all key-value pairs
[Link](k) Get value for key k (returns None if missing)
[Link](d2) Update with another dictionary
[Link](k) Remove and return value for key k
[Link]() Remove and return last inserted pair
[Link]() Remove all items
[Link]() Return a copy
[Link](k,v) Set key k to v only if k not already present
Traversing a Dictionary
for key in d:
print(key, ':', d[key])
for key, value in [Link]():
print(key, '=', value)
3.6 Sets
A set is an unordered collection of unique elements using curly braces {}.
• No duplicates allowed
• No indexing or slicing
• Elements must be immutable
• Create empty set with set() — not {} (that makes a dict!)
Set Operations
Operation Symbol Method
Union A|B [Link](B)
Intersection A&B [Link](B)
Difference A-B [Link](B)
Symmetric Diff A^B A.symmetric_difference(B)
Set Methods
• add(x) – add element x
• remove(x) – remove x; raises KeyError if not found
• discard(x) – remove x; no error if not found
• pop() – remove and return an arbitrary element
• clear() – remove all elements
Frozen Set
frozenset is an immutable version of set. Can be used as a dictionary key.
fs = frozenset([1, 2, 3])
Set Comprehension
squares = {x*x for x in range(1, 6)} # {1, 4, 9, 16, 25}
evens = {x for x in range(1,11) if x%2==0} # {2, 4, 6, 8, 10}
MODULE 4: Scientific Computing in Python
4.1 NumPy
NumPy (Numerical Python) provides fast, multi-dimensional array operations.
• All elements must be the same data type
• Faster than Python lists for numerical operations
Creating Arrays
import numpy as np
arr1 = [Link]([1, 2, 3]) # 1D array
arr2 = [Link]([[1,2,3],[4,5,6]]) # 2D array (matrix)
arr3 = [Link]((2,3)) # 2x3 array of zeros
arr4 = [Link]((3,2)) # 3x2 array of ones
arr5 = [Link](3) # 3x3 identity matrix
arr6 = [Link](0, 10, 2) # [0, 2, 4, 6, 8]
arr7 = [Link](0, 1, 5) # [0, 0.25, 0.5, 0.75, 1]
Array Attributes
[Link] # Dimensions tuple e.g. (2, 3)
[Link] # Number of dimensions
[Link] # Data type e.g. int64
[Link] # Total number of elements
Indexing & Slicing
arr = [Link]([10, 20, 30, 40, 50])
arr[0] # 10 (first)
arr[-1] # 50 (last)
arr[1:4] # [20, 30, 40]
mat = [Link]([[1,2,3],[4,5,6]])
mat[0, 1] # 2 (row 0, col 1)
mat[:, 1] # [2, 5] (all rows, col 1)
mat[0, :] # [1, 2, 3] (first row)
Array Operations
a = [Link]([1,2,3,4])
b = [Link]([10,20,30,40])
a + b # [11, 22, 33, 44]
a * b # [10, 40, 90, 160]
a ** 2 # [1, 4, 9, 16]
Aggregate Functions
Function Description
[Link](arr) Sum of all elements
[Link](arr) Average value
[Link](arr) Minimum value
[Link](arr) Maximum value
[Link](arr) Standard deviation
[Link](arr) Variance
Universal Functions (ufuncs)
• [Link](arr) – square root of each element
• [Link](arr) – exponential (e^x)
• [Link](arr) – natural logarithm
• [Link](arr), [Link](arr) – trigonometric
Broadcasting
Allows operations between arrays of different shapes by expanding smaller arrays:
a = [Link]([1, 2, 3])
a + 5 # [6, 7, 8] (scalar broadcast)
mat = [Link]([[1,2,3],[4,5,6],[7,8,9]])
row = [Link]([10,20,30])
mat + row # adds row to each row of mat
Fancy Indexing
arr = [Link]([10, 20, 30, 40, 50])
arr[[0, 2, 4]] # [10, 30, 50]
4.2 Pandas
Pandas is a library for data manipulation and analysis built on top of NumPy. Provides Series and
DataFrame structures.
Pandas Series
A one-dimensional labeled array:
import pandas as pd
s = [Link]([10, 20, 30]) # default index 0,1,2
s = [Link]([10,20,30], index=['a','b','c']) # custom index
s['b'] # 20
# From dictionary
data = {'A': 100, 'B': 200}
s = [Link](data) # keys become index
Pandas DataFrame
A two-dimensional table (rows and columns):
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['Kochi', 'Thrissur', 'Palakkad']
}
df = [Link](data)
df['Name'] # Access column
[Link][1] # Access row by integer index
[Link]['b'] # Access row by label
4.3 Matplotlib
Matplotlib is a Python library for creating static, animated, and interactive visualizations.
Components
• Figure – the overall window/canvas
• Axes – the area where data is plotted
• Axis – the x and y coordinate lines
• Labels & Titles – axes names and plot title
• Legends – identify multiple datasets
Types of Plots
Plot Type Function Use Case
Line Graph [Link](x, y) Trends over time / continuous data
Bar Chart [Link](x, y) Compare categories
Histogram [Link](data, bins=n) Frequency distribution
Scatter Plot [Link](x, y) Relationship between two variables
Pie Chart [Link](sizes, labels=labels) Proportions / percentages
Box Plot [Link](data) Distribution, median, quartiles, outliers
Basic Plot Template
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
[Link](x, y, label='Data', color='blue', linestyle='--', marker='o')
[Link]('X-axis')
[Link]('Y-axis')
[Link]('My Plot')
[Link]()
[Link]()
Customization Options
• color='red' / color='#FF0000'
• linestyle='--' (dashed), '-.' (dash-dot), ':' (dotted)
• marker='o' (circle), 's' (square), '^' (triangle)
• [Link](True) – add grid lines
4.4 Library Summary
Library Purpose Key Features
NumPy Numerical computing Fast arrays, broadcasting, ufuncs, linear algebra
Pandas Data analysis Series, DataFrame, CSV/Excel I/O, data cleaning
Matplotlib Visualization 6+ plot types, fully customizable, integrates with NumPy/Pandas
Quick Reference: Key Points for Exam
Important Definitions
Term Definition
Mutable Can be changed after creation (List, Dict, Set)
Immutable Cannot be changed (String, Tuple, Frozenset, int, float)
Hashing Technique used internally by Dict and Set for O(1) access
Broadcasting NumPy feature to operate on arrays of different shapes
ufunc Universal function in NumPy – fast element-wise operation
Series 1D labeled array in Pandas
DataFrame 2D labeled table in Pandas
Indexing Accessing element by position (starts at 0)
Slicing Extracting a portion using s[start:stop:step]
Comprehension Short syntax to create list/set from itererable with optional condition
Common Mistakes to Avoid
• {} creates an empty dict, NOT an empty set → use set()
• Single-element tuple needs a comma: (5,) not (5)
• Lists are mutable; strings and tuples are NOT
• Dictionary keys must be unique and hashable
• break skips the else block in loops
• [Link](start, stop, step) — stop is exclusive
• Negative indexing: s[-1] = last element, s[-2] = second last
Time Complexities
Structure Access Insert Delete Search
List O(1) O(1) end / O(n) middle O(n) O(n)
Dictionary O(1) avg O(1) avg O(1) avg O(1) avg
Set – O(1) avg O(1) avg O(1) avg
Tuple O(1) – – O(n)
★ Good Luck in Your Exam! ★