🐍 College Coders Python Notes
🐍
COLLEGE CODERS
PYTHON NOTES
Complete Guide from Basics to Projects
Topics Covered
✔ Introduction to Python
✔ Variables, Data Types & Operators
✔ Conditional Statements & Loops
✔ Functions in Python
✔ Lists, Tuples, Sets, Dictionaries
✔ String Manipulation & File Handling
✔ Exception Handling & OOP
✔ Modules, Packages & 12 Projects
College Coders Python Notes • Page
🐍 College Coders Python Notes
Chapter 1: Introduction to Python
🐍 Definition: Python
Python is a high-level, interpreted, general-purpose programming language created by
Guido van Rossum and released in 1991. It emphasizes code readability and simplicity,
using indentation to define code blocks.
Why Python?
Python is one of the most popular languages in the world. Here's why:
• Easy to learn and read — syntax is close to plain English
• Versatile — used in web development, data science, AI, automation, and more
• Large community — millions of developers and libraries available
• Free & Open Source — anyone can use and contribute
1.1 Installing Python & VS Code
Step 1 — Install Python
1. Go to [Link]
2. Download the latest version (e.g., Python 3.12)
3. Run the installer — CHECK the box 'Add Python to PATH'
4. Click 'Install Now'
5. Open Command Prompt and verify:
🐍 Verify Python Installation
python --version
# Output: Python 3.12.x
Step 2 — Install VS Code
1. Go to [Link]
2. Download and install for your OS
3. Open VS Code → Extensions (Ctrl+Shift+X) → Search 'Python' → Install Microsoft Python extension
4. Create a new file named [Link] and write:
🐍 Your First Python Program
print("Hello, World!")
🐍 Explanation: The print() function displays output on the screen. This is traditionally the
first program every coder writes!
College Coders Python Notes • Page
🐍 College Coders Python Notes
Chapter 2: Variables and Data Types
🐍 Definition: Variable
A variable is a named container that stores data in memory. In Python, you do not need to
declare the type — Python figures it out automatically.
2.1 Creating Variables
🐍 Variable Examples
name = 'Alice' # String
age = 20 # Integer
marks = 95.5 # Float
is_student = True # Boolean
print(name) # Alice
print(age) # 20
print(marks) # 95.5
print(is_student) # True
🐍 Explanation: Python automatically detects the type of data. name stores text (str), age
stores a whole number (int), marks stores a decimal (float), and is_student stores True/False
(bool).
2.2 Data Types in Python
Data Type Example Description
int x = 10 Whole numbers (no decimal)
float x = 3.14 Decimal numbers
str x = 'Hi' Text / sequence of characters
bool x = True True or False values
list x = [1, 2, 3] Ordered, changeable collection
tuple x = (1, 2, 3) Ordered, unchangeable collection
set x = {1, 2, 3} Unordered, no duplicates
dict x = {'a': 1} Key-value pairs
NoneType x = None Represents absence of value
2.3 Type Checking & Conversion
🐍 type() and Type Conversion
x = 10
print(type(x)) # <class 'int'>
# Type Conversion
College Coders Python Notes • Page
🐍 College Coders Python Notes
a = str(10) # '10' (int to string)
b = int('25') # 25 (string to int)
c = float('3.14') # 3.14 (string to float)
d = bool(0) # False (0 is False)
e = bool(1) # True (non-zero is True)
🐍 Explanation: type() tells you what kind of data a variable holds. Conversion functions like
int(), str(), float() let you change data from one type to another.
2.4 Taking User Input
🐍 input() Function
name = input('Enter your name: ')
age = int(input('Enter your age: '))
print('Hello,', name)
print('You are', age, 'years old')
🐍 Explanation: input() always returns a string. If you need a number, convert it with int() or
float().
Chapter 3: Operators in Python
🐍 Definition: Operator
Operators are special symbols used to perform operations on values and variables. Python
has several types of operators.
3.1 Arithmetic Operators
🐍 Arithmetic Operators
a = 15
b = 4
print(a + b) # 19 (Addition)
print(a - b) # 11 (Subtraction)
print(a * b) # 60 (Multiplication)
print(a / b) # 3.75 (Division - always float)
print(a // b) # 3 (Floor Division - no decimal)
print(a % b) # 3 (Modulus - remainder)
print(a ** b) # 50625 (Exponent - a to the power b)
3.2 Comparison Operators
🐍 Comparison Operators — Return True or False
x = 10
y = 20
print(x == y) # False (Equal to)
print(x != y) # True (Not equal to)
print(x > y) # False (Greater than)
College Coders Python Notes • Page
🐍 College Coders Python Notes
print(x < y) # True (Less than)
print(x >= y) # False (Greater than or equal)
print(x <= y) # True (Less than or equal)
3.3 Logical Operators
🐍 Logical Operators — and, or, not
a = True
b = False
print(a and b) # False (Both must be True)
print(a or b) # True (At least one True)
print(not a) # False (Reverses the value)
# Practical example
age = 20
has_id = True
print(age >= 18 and has_id) # True
3.4 Assignment Operators
🐍 Assignment Operators
x = 10
x += 5 # x = x + 5 → 15
x -= 3 # x = x - 3 → 12
x *= 2 # x = x * 2 → 24
x /= 4 # x = x / 4 → 6.0
x //= 2 # x = x // 2 → 3.0
x **= 3 # x = x ** 3 → 27.0
x %= 5 # x = x % 5 → 2.0
3.5 Identity & Membership Operators
🐍 is, in Operators
# Identity
a = [1, 2]
b = a
print(a is b) # True (same object in memory)
# Membership
fruits = ['apple', 'mango', 'banana']
print('mango' in fruits) # True
print('grape' not in fruits) # True
🐍 Explanation: 'in' checks if a value exists inside a list, string, tuple, etc. 'is' checks if two
variables point to the exact same memory object.
Chapter 4: Conditional Statements
🐍 Definition: Conditional Statement
College Coders Python Notes • Page
🐍 College Coders Python Notes
Conditional statements allow the program to make decisions and execute different code
based on whether a condition is True or False.
4.1 if Statement
🐍 Basic if Statement
age = 18
if age >= 18:
print('You are eligible to vote.')
🐍 Explanation: The code inside the if block runs only when the condition (age >= 18) is
True. Python uses indentation (4 spaces or a tab) to define the block.
4.2 if-else Statement
🐍 if-else Statement
marks = 45
if marks >= 50:
print('Result: PASS')
else:
print('Result: FAIL')
🐍 Explanation: The else block runs when the if condition is False. Only one of the two
blocks will execute.
4.3 if-elif-else Statement
🐍 if-elif-else — Multiple Conditions
marks = 75
if marks >= 90:
grade = 'A+'
elif marks >= 80:
grade = 'A'
elif marks >= 70:
grade = 'B'
elif marks >= 60:
grade = 'C'
else:
grade = 'F'
print('Grade:', grade) # Grade: B
🐍 Explanation: elif stands for 'else if'. Python checks conditions one by one from top to
bottom and runs the first matching block. The else runs if nothing matches.
4.4 Nested if Statements
🐍 Nested if
College Coders Python Notes • Page
🐍 College Coders Python Notes
num = 15
if num > 0:
print('Positive number')
if num % 2 == 0:
print('Even')
else:
print('Odd')
else:
print('Negative or Zero')
4.5 Ternary Operator (One-line if-else)
🐍 Ternary / Conditional Expression
age = 20
status = 'Adult' if age >= 18 else 'Minor'
print(status) # Adult
🐍 Explanation: This is a shorthand way to write if-else in a single line. Format: value_if_true
if condition else value_if_false
Chapter 5: Loops in Python
🐍 Definition: Loop
A loop is used to execute a block of code repeatedly until a certain condition is met. Python
has two types: for loop and while loop.
5.1 for Loop
🐍 for Loop — Iterating over a range
# Print numbers 1 to 5
for i in range(1, 6):
print(i)
# Output:
# 1
# 2
# 3
# 4
# 5
🐍 Explanation: range(1, 6) generates numbers from 1 to 5 (6 is excluded). The for loop
runs once for each value in that range.
5.2 Iterating over Collections
🐍 for Loop over List and String
# Over a list
fruits = ['apple', 'mango', 'banana']
for fruit in fruits:
College Coders Python Notes • Page
🐍 College Coders Python Notes
print(fruit)
# Over a string
for char in 'Python':
print(char)
5.3 while Loop
🐍 while Loop
count = 1
while count <= 5:
print('Count:', count)
count += 1 # Important: update variable!
# Output: Count: 1, Count: 2 ... Count: 5
🐍 Explanation: The while loop keeps running as long as the condition is True. Always make
sure the condition will eventually become False, otherwise you get an infinite loop!
5.4 break and continue
🐍 break — Exit the Loop Early
for i in range(1, 11):
if i == 5:
break # Stop when i is 5
print(i)
# Output: 1 2 3 4
🐍 continue — Skip Current Iteration
for i in range(1, 8):
if i == 4:
continue # Skip 4
print(i)
# Output: 1 2 3 5 6 7
5.5 Nested Loops
🐍 Nested for Loop — Multiplication Table
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=' ')
print() # New line after each row
# Output:
# 1 2 3
# 2 4 6
# 3 6 9
5.6 else with Loops
🐍 Loop else — Runs when loop completes normally
for i in range(1, 6):
College Coders Python Notes • Page
🐍 College Coders Python Notes
print(i)
else:
print('Loop finished!')
# The else block does NOT run if break was used
Chapter 6: Functions in Python
🐍 Definition: Function
A function is a reusable block of code that performs a specific task. Functions help organize
code, avoid repetition, and make programs easier to read and test.
6.1 Defining and Calling a Function
🐍 Basic Function
def greet():
print('Hello! Welcome to Python.')
greet() # Calling the function
# Output: Hello! Welcome to Python.
6.2 Function with Parameters
🐍 Function with Parameters
def greet(name):
print(f'Hello, {name}! How are you?')
greet('Alice') # Hello, Alice! How are you?
greet('Bob') # Hello, Bob! How are you?
6.3 Function with Return Value
🐍 Function Returning a Value
def add(a, b):
return a + b
result = add(10, 20)
print('Sum:', result) # Sum: 30
6.4 Default Parameters
🐍 Default Parameter Values
def greet(name, message='Good Morning'):
print(f'{message}, {name}!')
greet('Alice') # Good Morning, Alice!
greet('Bob', 'Good Evening') # Good Evening, Bob!
College Coders Python Notes • Page
🐍 College Coders Python Notes
🐍 Explanation: If you don't pass a value for 'message', Python uses the default 'Good
Morning'. Default parameters must come after non-default ones.
6.5 Keyword Arguments
🐍 Keyword Arguments
def student_info(name, age, course):
print(f'{name} | Age: {age} | Course: {course}')
# Call with keyword arguments (order doesn't matter)
student_info(course='Python', name='Alice', age=20)
6.6 *args — Variable Number of Arguments
🐍 *args — Accepts Multiple Positional Arguments
def total(*numbers):
result = 0
for n in numbers:
result += n
return result
print(total(1, 2, 3)) # 6
print(total(5, 10, 15, 20)) # 50
🐍 Explanation: *args lets you pass any number of arguments. They're collected as a tuple
inside the function.
6.7 **kwargs — Keyword Variable Arguments
🐍 **kwargs — Accepts Multiple Keyword Arguments
def show_info(**details):
for key, value in [Link]():
print(f'{key}: {value}')
show_info(name='Alice', age=20, city='Delhi')
# name: Alice
# age: 20
# city: Delhi
6.8 Lambda Functions
🐍 Definition: Lambda Function
A lambda is a small anonymous (unnamed) function defined in a single line using the
lambda keyword.
🐍 Lambda Function
# Normal function
def square(x):
return x ** 2
College Coders Python Notes • Page
🐍 College Coders Python Notes
# Lambda equivalent
square = lambda x: x ** 2
print(square(5)) # 25
# Lambda with two arguments
add = lambda a, b: a + b
print(add(3, 7)) # 10
6.9 Recursive Functions
🐍 Definition: Recursion
A recursive function is one that calls itself to solve a smaller version of the same problem.
🐍 Recursive Function — Factorial
def factorial(n):
if n == 0 or n == 1:
return 1 # Base case
return n * factorial(n - 1) # Recursive call
print(factorial(5)) # 120 (5*4*3*2*1)
6.10 Scope: Local vs Global Variables
🐍 Variable Scope
x = 100 # Global variable
def show():
y = 50 # Local variable
print('Inside:', x, y)
show() # Inside: 100 50
print('Outside:', x) # Outside: 100
# print(y) # Error! y is not accessible here
6.11 Higher-Order Functions (map, filter, reduce)
🐍 map(), filter(), reduce()
# map() — Apply a function to every item
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
print(squares) # [1, 4, 9, 16, 25]
# filter() — Keep items where function returns True
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4]
# reduce() — Reduce list to single value
from functools import reduce
total = reduce(lambda a, b: a + b, nums)
print(total) # 15
College Coders Python Notes • Page
🐍 College Coders Python Notes
Chapter 7: Lists, Tuples, Sets & Dictionaries
7.1 Lists
🐍 Definition: List
A list is an ordered, mutable (changeable) collection of items. Lists can contain items of
different types and allow duplicates. Defined with square brackets [].
🐍 List Operations
fruits = ['apple', 'mango', 'banana', 'orange']
print(fruits[0]) # apple (indexing)
print(fruits[-1]) # orange (last item)
print(fruits[1:3]) # ['mango', 'banana'] (slicing)
print(len(fruits)) # 4
# Modifying lists
[Link]('grape') # Add to end
[Link](1, 'cherry') # Insert at index 1
[Link]('mango') # Remove by value
[Link]() # Remove last item
[Link](0) # Remove by index
# Other methods
[Link]() # Sort alphabetically
[Link]() # Reverse the list
print([Link]('apple')) # Count occurrences
print([Link]('banana'))# Find index
7.2 List Comprehension
🐍 List Comprehension — Powerful one-liner
# Old way
squares = []
for x in range(1, 6):
[Link](x**2)
# List comprehension way
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With condition
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
7.3 Tuples
🐍 Definition: Tuple
A tuple is an ordered, immutable (unchangeable) collection. Once created, you cannot add,
remove, or change items. Defined with parentheses ().
College Coders Python Notes • Page
🐍 College Coders Python Notes
🐍 Tuple Operations
coordinates = (10.5, 20.3, 30.1)
print(coordinates[0]) # 10.5
print(len(coordinates)) # 3
print(coordinates[1:]) # (20.3, 30.1)
# Tuple unpacking
x, y, z = coordinates
print(x, y, z) # 10.5 20.3 30.1
# Single-item tuple needs a comma!
single = (42,) # NOT (42) — that's just parentheses
🐍 Explanation: Use tuples when data should not change, like coordinates, RGB colors, or
database records. Tuples are also faster than lists.
7.4 Sets
🐍 Definition: Set
A set is an unordered collection of unique items. Sets automatically remove duplicate values
and do not support indexing. Defined with curly braces {}.
🐍 Set Operations
nums = {1, 2, 3, 4, 4, 5, 5}
print(nums) # {1, 2, 3, 4, 5} — duplicates removed
[Link](6) # Add element
[Link](3) # Remove element (error if not found)
[Link](10) # Remove safely (no error)
# 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: {1,2,5,6}
7.5 Dictionaries
🐍 Definition: Dictionary
A dictionary is an unordered collection of key-value pairs. Keys must be unique and
immutable. Values can be anything. Defined with curly braces {}.
🐍 Dictionary Operations
student = {
'name': 'Alice',
'age': 20,
'marks': 95.5,
'courses': ['Python', 'Java']
}
College Coders Python Notes • Page
🐍 College Coders Python Notes
# Accessing values
print(student['name']) # Alice
print([Link]('age', 0)) # 20 (safe access)
# Modifying
student['age'] = 21 # Update
student['city'] = 'Mumbai' # Add new key
del student['marks'] # Delete key
# Iterating
for key, value in [Link]():
print(f'{key}: {value}')
print([Link]()) # All keys
print([Link]()) # All values
7.6 Comparison Table
Feature List Tuple Set Dict
Ordered ✅ Yes ✅ Yes ❌ No ✅ Yes (3.7+)
Mutable ✅ Yes ❌ No ✅ Yes ✅ Yes
Duplicates ✅ Yes ✅ Yes ❌ No Keys: ❌
Indexable ✅ Yes ✅ Yes ❌ No By Key
Syntax [1,2,3] (1,2,3) {1,2,3} {'k':'v'}
Chapter 8: String Manipulation
🐍 Definition: String
A string is a sequence of characters enclosed in single quotes (''), double quotes (""), or
triple quotes (''' ''' or """ """). Strings are immutable in Python.
8.1 String Basics
🐍 String Creation and Access
text = 'Hello, Python!'
print(text[0]) # H (indexing)
print(text[-1]) # ! (last character)
print(text[0:5]) # Hello (slicing)
print(text[7:]) # Python!
print(len(text)) # 15
print([Link]()) # HELLO, PYTHON!
print([Link]()) # hello, python!
8.2 String Methods
🐍 Common String Methods
College Coders Python Notes • Page
🐍 College Coders Python Notes
s = ' Hello, World! '
print([Link]()) # 'Hello, World!' (remove spaces)
print([Link]()) # 'Hello, World! '
print([Link]()) # ' Hello, World!'
print([Link]('World','Python')) # ' Hello, Python! '
print([Link]('World')) # 9 (index or -1 if not found)
print([Link]('l')) # 3
print('hello'.capitalize()) # Hello
print('Hello World'.title()) # Hello World
print('hello'.startswith('he')) # True
print('hello'.endswith('lo')) # True
8.3 String Splitting and Joining
🐍 split() and join()
# Split a string into a list
sentence = 'Python is amazing'
words = [Link](' ') # ['Python', 'is', 'amazing']
csv_line = '1,2,3,4'
nums = csv_line.split(',') # ['1', '2', '3', '4']
# Join a list into a string
joined = ' '.join(['Hello', 'World']) # 'Hello World'
csv = ','.join(['a', 'b', 'c']) # 'a,b,c'
8.4 String Formatting
🐍 f-strings (Recommended), format(), % operator
name = 'Alice'
age = 20
marks = 95.567
# f-string (Python 3.6+) — Recommended
print(f'Name: {name}, Age: {age}')
print(f'Marks: {marks:.2f}') # 95.57 (2 decimal places)
# .format() method
print('Name: {}, Age: {}'.format(name, age))
# % operator (older style)
print('Name: %s, Age: %d' % (name, age))
8.5 Escape Characters
🐍 Escape Characters in Strings
print('Hello\nWorld') # New line
print('Hello\tWorld') # Tab space
print('She said \'Hi\'') # Quotes inside string
print('C:\\Users\\Alice') # Backslash
# Raw string — ignores escape characters
path = r'C:\Users\Alice\Documents'
print(path) # C:\Users\Alice\Documents
College Coders Python Notes • Page
🐍 College Coders Python Notes
8.6 String Checking Methods
🐍 isdigit(), isalpha(), isalnum(), etc.
print('123'.isdigit()) # True
print('abc'.isalpha()) # True
print('abc123'.isalnum()) # True
print(' '.isspace()) # True
print('HELLO'.isupper()) # True
print('hello'.islower()) # True
Chapter 9: File Handling
🐍 Definition: File Handling
File handling in Python allows you to create, read, write, and manage files on your
computer's storage. Python provides built-in functions and methods to work with files.
9.1 Opening and Closing Files
🐍 open() Function and File Modes
# File modes:
# 'r' — Read (default). Error if file doesn't exist.
# 'w' — Write. Creates file, OVERWRITES if exists.
# 'a' — Append. Creates file, adds to end if exists.
# 'x' — Create. Error if file already exists.
# 'rb' — Read in binary mode.
# Old way — must close manually
file = open('[Link]', 'r')
[Link]()
# Best way — using 'with' (auto-closes)
with open('[Link]', 'r') as file:
content = [Link]()
print(content)
🐍 Explanation: Always use 'with open(...)' — it automatically closes the file even if an error
occurs. This prevents data loss and file corruption.
9.2 Writing to a File
🐍 Writing and Appending
# Write (creates new file or overwrites existing)
with open('[Link]', 'w') as f:
[Link]('Hello, File!\n')
[Link]('Second line.\n')
# Append to existing file
with open('[Link]', 'a') as f:
[Link]('This is appended.\n')
College Coders Python Notes • Page
🐍 College Coders Python Notes
# Write multiple lines at once
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('[Link]', 'w') as f:
[Link](lines)
9.3 Reading from a File
🐍 Reading Methods
with open('[Link]', 'r') as f:
# read() — Reads entire file as one string
content = [Link]()
with open('[Link]', 'r') as f:
# readline() — Reads one line at a time
line1 = [Link]()
line2 = [Link]()
with open('[Link]', 'r') as f:
# readlines() — Returns list of all lines
lines = [Link]()
for line in lines:
print([Link]())
9.4 Working with File Paths using os module
🐍 os Module for File Management
import os
# Check if file exists
print([Link]('[Link]')) # True or False
# Get file size in bytes
print([Link]('[Link]'))
# Rename a file
[Link]('[Link]', 'my_notes.txt')
# Delete a file
[Link]('my_notes.txt')
# List files in a directory
print([Link]('.'))
# Create a directory
[Link]('my_folder')
Chapter 10: Exception Handling
🐍 Definition: Exception
College Coders Python Notes • Page
🐍 College Coders Python Notes
An exception is an error that occurs during program execution. Exception handling lets you
catch errors gracefully and keep your program running instead of crashing.
10.1 try-except Block
🐍 Basic try-except
try:
number = int(input('Enter a number: '))
print('You entered:', number)
except ValueError:
print('Error! That is not a valid number.')
🐍 Explanation: The code inside 'try' is executed. If an error occurs, Python jumps to the
'except' block instead of crashing. A ValueError occurs when trying to convert invalid input
like 'abc' to int.
10.2 Multiple except Blocks
🐍 Handling Different Error Types
try:
a = int(input('Numerator: '))
b = int(input('Denominator: '))
result = a / b
print('Result:', result)
except ValueError:
print('Please enter valid numbers!')
except ZeroDivisionError:
print('Cannot divide by zero!')
except Exception as e:
print('Unexpected error:', e)
10.3 else and finally
🐍 try-except-else-finally
try:
file = open('[Link]', 'r')
content = [Link]()
except FileNotFoundError:
print('File not found!')
else:
print('File read successfully!')
print(content)
finally:
print('This runs no matter what.')
🐍 Explanation: 'else' runs only when NO exception occurred. 'finally' ALWAYS runs —
perfect for cleanup tasks like closing files or database connections.
10.4 Common Python Exceptions
College Coders Python Notes • Page
🐍 College Coders Python Notes
Exception Description
ValueError Invalid value (e.g., int('abc'))
TypeError Wrong data type used
ZeroDivisionError Division by zero
FileNotFoundError File does not exist
IndexError List index out of range
KeyError Dictionary key not found
NameError Variable not defined
AttributeError Object has no such attribute
ImportError Module cannot be imported
OverflowError Number too large for computation
10.5 Raising Custom Exceptions
🐍 raise — Manually Trigger an Exception
def check_age(age):
if age < 0:
raise ValueError('Age cannot be negative!')
return age
try:
check_age(-5)
except ValueError as e:
print('Error:', e) # Error: Age cannot be negative!
Chapter 11: Object-Oriented Programming (OOP)
🐍 Definition: OOP
Object-Oriented Programming is a programming paradigm that organizes code into objects
that combine data (attributes) and behavior (methods). The four pillars of OOP are:
Encapsulation, Inheritance, Polymorphism, and Abstraction.
11.1 Classes and Objects
🐍 Creating a Class and Object
class Student:
# Constructor method — runs when object is created
def __init__(self, name, age, marks):
[Link] = name # Instance attribute
[Link] = age
[Link] = marks
# Method — function inside a class
def display(self):
print(f'Name: {[Link]}, Age: {[Link]}, Marks: {[Link]}')
College Coders Python Notes • Page
🐍 College Coders Python Notes
def grade(self):
if [Link] >= 90:
return 'A'
elif [Link] >= 75:
return 'B'
else:
return 'C'
# Creating objects (instances)
s1 = Student('Alice', 20, 92)
s2 = Student('Bob', 21, 78)
[Link]() # Name: Alice, Age: 20, Marks: 92
print([Link]()) # A
🐍 Explanation: A class is a blueprint; an object is an instance of that blueprint. 'self' refers
to the current object. __init__ is called automatically when you create an object.
11.2 Inheritance
🐍 Definition: Inheritance
Inheritance allows a new class (child) to acquire the properties and methods of an existing
class (parent). This promotes code reuse.
🐍 Inheritance Example
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
print(f'{[Link]} makes a sound.')
# Dog inherits from Animal
class Dog(Animal):
def speak(self): # Overriding parent method
print(f'{[Link]} says: Woof!')
class Cat(Animal):
def speak(self):
print(f'{[Link]} says: Meow!')
d = Dog('Rex')
c = Cat('Whiskers')
[Link]() # Rex says: Woof!
[Link]() # Whiskers says: Meow!
11.3 super() — Calling Parent Constructor
🐍 super() Function
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
College Coders Python Notes • Page
🐍 College Coders Python Notes
class Employee(Person):
def __init__(self, name, age, emp_id):
super().__init__(name, age) # Call parent __init__
self.emp_id = emp_id
def display(self):
print(f'ID: {self.emp_id} | {[Link]} | Age: {[Link]}')
e = Employee('Alice', 30, 'E001')
[Link]() # ID: E001 | Alice | Age: 30
11.4 Encapsulation
🐍 Definition: Encapsulation
Encapsulation hides internal data of an object from outside access. Private attributes use
double underscore (__). This protects data integrity.
🐍 Encapsulation with Private Attributes
class BankAccount:
def __init__(self, owner, balance):
[Link] = owner
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
else:
print('Insufficient funds!')
def get_balance(self):
return self.__balance
acc = BankAccount('Alice', 5000)
[Link](2000)
print(acc.get_balance()) # 7000
# print(acc.__balance) # AttributeError! Private
11.5 Polymorphism
🐍 Definition: Polymorphism
Polymorphism means 'many forms'. The same method name can behave differently in
different classes. Python achieves this through method overriding.
🐍 Polymorphism Example
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, r):
College Coders Python Notes • Page
🐍 College Coders Python Notes
self.r = r
def area(self):
return 3.14 * self.r ** 2
class Rectangle(Shape):
def __init__(self, l, w):
self.l = l; self.w = w
def area(self):
return self.l * self.w
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(f'Area: {[Link]()}')
# Area: 78.5
# Area: 24
11.6 Abstraction
🐍 Definition: Abstraction
Abstraction hides complex implementation details and shows only essential features. Python
uses Abstract Base Classes (ABC) from the abc module.
🐍 Abstract Class
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self): # Must be implemented by subclass
pass
class Car(Vehicle):
def start(self):
print('Car started with key.')
class Bike(Vehicle):
def start(self):
print('Bike started with button.')
# v = Vehicle() # Error! Cannot instantiate abstract class
car = Car()
[Link]() # Car started with key.
11.7 Special (Dunder) Methods
🐍 __str__, __len__, __add__ and more
class Book:
def __init__(self, title, pages):
[Link] = title
[Link] = pages
def __str__(self): # Called by print()
return f'Book: {[Link]}'
def __len__(self): # Called by len()
return [Link]
College Coders Python Notes • Page
🐍 College Coders Python Notes
def __add__(self, other): # Called by +
return [Link] + [Link]
b1 = Book('Python Basics', 300)
b2 = Book('Advanced Python', 450)
print(b1) # Book: Python Basics
print(len(b1)) # 300
print(b1 + b2) # 750
11.8 Class vs Static Methods
🐍 @classmethod and @staticmethod
class MathHelper:
pi = 3.14159 # Class attribute
@classmethod
def circle_area(cls, r): # cls = the class itself
return [Link] * r ** 2
@staticmethod
def add(a, b): # No self or cls needed
return a + b
print(MathHelper.circle_area(5)) # 78.53975
print([Link](10, 20)) # 30
Chapter 12: Modules & Packages
🐍 Definition: Module
A module is a Python file (.py) containing code — functions, classes, and variables — that
can be imported and used in other Python files. A package is a folder containing multiple
modules with an __init__.py file.
12.1 Importing Modules
🐍 import and from-import
# Import entire module
import math
print([Link]) # 3.141592653589793
print([Link](16)) # 4.0
print([Link](4.2)) # 5
print([Link](4.8)) # 4
# Import specific items
from math import pi, sqrt, factorial
print(pi) # 3.14159...
print(factorial(5)) # 120
# Import with alias
import math as m
College Coders Python Notes • Page
🐍 College Coders Python Notes
print([Link](2, 8)) # 256.0
12.2 Creating Your Own Module
🐍 [Link] — Create this file
# [Link]
def greet(name):
return f'Hello, {name}!'
def add(a, b):
return a + b
PI = 3.14159
🐍 [Link] — Import and use your module
# [Link]
import mymodule
print([Link]('Alice')) # Hello, Alice!
print([Link](5, 10)) # 15
print([Link]) # 3.14159
12.3 Useful Built-in Modules
Module What it does
math Mathematical functions: sqrt, pi, sin, cos, ceil, floor, factorial
random Random numbers: random(), randint(), choice(), shuffle()
datetime Dates and times: [Link](), [Link](), timedelta
os Operating system: file/folder operations, paths, environment
sys System-specific: argv, path, version, exit()
json JSON encoding/decoding: dumps(), loads(), dump(), load()
time Time operations: sleep(), time(), ctime()
re Regular expressions: search(), match(), findall(), sub()
collections Specialized data structures: Counter, deque, OrderedDict
itertools Iterators: combinations, permutations, product, chain
12.4 Installing Third-Party Packages with pip
🐍 pip — Python Package Installer
# Install a package
pip install requests
# Install specific version
pip install requests==2.28.0
# List installed packages
pip list
College Coders Python Notes • Page
🐍 College Coders Python Notes
# Uninstall a package
pip uninstall requests
# Save dependencies to file
pip freeze > [Link]
# Install from requirements file
pip install -r [Link]
12.5 Popular Third-Party Libraries
🐍 Quick Examples
# requests — HTTP requests
import requests
response = [Link]('[Link]
print(response.status_code) # 200
# numpy — Numerical computing
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print([Link]()) # 3.0
# pandas — Data analysis
import pandas as pd
df = [Link]({'name': ['Alice', 'Bob'], 'age': [20, 21]})
print([Link]())
🐍 12 PYTHON PROJECTS
Watch all 12 projects on YouTube
[Link]
M3357lCFXVL&si=crhWhpdi0BpF_FYA
🐍 Congratulations!
You have completed the College Coders Python Notes!
Keep coding, keep building, keep learning! 🐍
— College Coders Team
College Coders Python Notes • Page