My Notes

Python Notes

Table of Content

PHASE 1: CORE FOUNDATIONS OF PYTHON


PHASE 2: DATA HANDLING IN PYTHON


PHASE 3: OPERATORS & EXPRESSIONS


PHASE 4: CONTROL FLOW


PHASE 5: FUNCTIONS & RECURSION


PHASE 6: PYTHON ADVANCED


PHASE 7: OOPS IN PYTHON


PHASE 8: EXCEPTION HANDLING & FILES


PHASE 1: CORE FOUNDATIONS OF PYTHON

What is Python? (Human Explanation)

Imagine you want to talk to your computer.

C / Java β†’ you must speak very formally, like writing a legal contract

Python β†’ you talk like a normal human

πŸ‘‰ Python is a high-level programming language

  • You don’t worry about memory, registers, CPU stuff
  • You focus on logic, not machine headache

Why Python became so popular?

β€œCode should look like plain English.”

print("Hello World")

Looks like something a human would write, not a robot.

Why Python is Interpreted (Very Important)

Let’s use a real-life analogy πŸ‘‡

🎀 Compiled Language (C, C++)

  • You finish entire song
  • Producer checks errors
  • Then it’s released
  • Mistake at line 500 β†’ found after everything

🎧 Interpreted Language (Python)

  • You sing line by line
  • Error appears immediately

πŸ‘‰ Python runs one line at a time

  • Debugging is easier
  • Beginners love Python
  • Error shows exact location

πŸ“Œ Python uses an interpreter, not a compiler.

Python vs C vs Java (Engineering Reality)

FeaturePythonCJava
TypeInterpretedCompiledHybrid
TypingDynamicStaticStatic
SyntaxSimpleComplexModerate
SpeedSlowFastestFast
  • C β†’ talk to hardware
  • Java β†’ big company systems
  • Python β†’ get work done fast

Keywords (Python’s Reserved Words)

Keywords are reserved seats in a train πŸš† β€” already booked.

You cannot use them as variable or function names.

and, as, break, class, continue, def, elif, else, False, for, if, import, lambda, None, not, or, pass, raise, return, True, try, while

Identifiers (Naming Things Like a Sane Engineer)

  • Names given to variables, functions, classes
  • Can contain letters, numbers, underscore
  • Cannot start with number
  • Cannot be a keyword
  • Case-sensitive
age = 20 _age = 30 # 2age = 40 ❌

Comments (Talking to Future You)

  • Used for documentation
  • Ignored by Python
# single line comment """ multi line comment """

Indentation – Python’s Backbone 🦴

Python uses indentation instead of curly braces.

Your code structure = your indentation

Variables (Python’s Superpower)

x = 10 name = "Python"

Python decides the type automatically.

Dynamic Typing

x = 10 x = "Hello"

Same variable, different type β€” decided at runtime.

type() Function

type(10) type("hello")

MCQ gold + debugging gold

🧠 PHASE 2: DATA HANDLING IN PYTHON

(This phase decides whether Python feels easy or confusing)

Think of data types as different containers in a lab πŸ§ͺ. You don’t store acid in a plastic bag, right? Same logic β€” different data β†’ different containers.

What is a Data Type? (Real Meaning)

  • What kind of data you are storing
  • What operations are allowed on it
x = 10

β€œOkay, this is a number. I can do math with it.”

NUMERIC DATA TYPES

(Used everywhere in engineering)

int – Integer (Solid Numbers)

πŸ‘‰ Whole numbers (no decimal)

a = 10 b = -5 c = 0

πŸ’‘ Engineering analogy:

  • Number of students
  • Number of sensors
  • Count of iterations

πŸ“Œ Special thing in Python:

Python integers have no size limit. Unlike C where int can overflow, Python says:

β€œRelax, I got this.”

float – Decimal Numbers

x = 3.14 y = 10.5

Used for:

  • Voltage
  • Temperature
  • Speed
  • Measurements

⚠️ Important concept:

0.1 + 0.2 != 0.3

Because floats are stored in binary approximation.

Like measuring with a scale that rounds values.

complex – Engineering-Level Numbers

z = 3 + 4j
  • 3 β†’ real part
  • 4j β†’ imaginary part

Used in:

  • Electrical engineering
  • Signal processing
z.real   # 3.0 z.imag   # 4.0

πŸ“Œ Python uses j, not i.

STRING (str) – Text Data

What is a String?

A string is a sequence of characters.

s = "Python"

Used for:

  • Names
  • Messages
  • File paths
  • URLs

String Indexing

s = "Python" s[0]   # P s[1]   # y s[-1]  # n

Like accessing pins on a microcontroller β€” each pin has a number.

String Slicing (πŸ”₯ VERY IMPORTANT)

string[start : end : step]
s = "Python" s[0:4]    # Pyth s[::2]    # Pto s[::-1]   # reverse

Like cutting a wire from point A to B.

Strings are IMMUTABLE

s = "hello" s[0] = "H"   # ❌ error

You must create a new string.

Strings are like engraved metal plates β€” you can’t edit, only replace.

COLLECTION DATA TYPES

(This is where Python becomes powerful)

list – The Toolbox 🧰

l = [1, 2, 3, "hi", 5.5] l[0] = 100
  • Ordered
  • Mutable
  • Allows duplicates
  • Mixed data

Like a toolbox β€” add or remove tools anytime.

tuple – Sealed Box πŸ“¦

t = (1, 2, 3) t = (5,)
  • Immutable
  • Faster
  • Safer

Like sealed factory product β€” don’t open it.

set – Unique Collection 🎯

s = {1, 2, 3, 3, 4}

Properties:

  • Unordered
  • No duplicates
  • Mutable
  • No indexing

dict – Real Database πŸ—„οΈ

d = {"name": "Alex", "age": 20}
  • Key-value pairs
  • Fast lookup
  • Keys must be unique & immutable

Like student database: Roll No β†’ Student Data

Mutable vs Immutable (MCQ GOLD)

Data TypeMutable?
int❌
float❌
str❌
tuple❌
listβœ…
setβœ…
dictβœ…
  • Mutable β†’ same memory, content changes
  • Immutable β†’ new memory created

🧠 PHASE 3: OPERATORS & EXPRESSIONS

(This phase is all about how Python thinks before giving output)

Think of operators as tools and expressions as circuits made using those tools βš™οΈβš‘

What is an Operator?

An operator is something that does an action.

10 + 5
  • 10, 5 β†’ operands (data)
  • + β†’ operator (action)

πŸ’‘ Real life:

  • Numbers are components
  • Operator is the connection

Arithmetic Operators

OperatorMeaningExampleResult
+Add5+27
-Subtract5-23
*Multiply5*210
/Divide5/22.5
//Floor5//22
%Modulus5%21
**Power2**38

Logical Operators

10 and 20   # 20  
0 and 20 # 0
10 or 20 # 10
0 or 20 # 20
  • and β†’ first False or last True
  • or β†’ first True

Operator Precedence

  • ()
  • **
  • * / // %
  • + -
  • == != > <
  • and
  • or

🧠 PHASE 4: CONTROL FLOW

Control flow decides when code runs, how many times it runs, and when to stop.

if Statement

if temperature > 30: print("Turn on fan")

Like sensor threshold logic.

if – else

if marks >= 40: print("Pass") else: print("Fail")

Loops

for i in range(5): print(i)
i = 1 while i <= 5: print(i) i += 1

break / continue / pass

for i in range(5): if i == 2: continue print(i)

🧠 PHASE 5: FUNCTIONS & RECURSION

(This phase teaches Python how to reuse intelligence)

Think of this phase as moving from messy wires to well-designed modules πŸ”Œβž‘οΈπŸ“¦

Why Do We Need Functions?

a = 10 b = 20 print(a + b)

Now imagine doing this 100 times 😡

A function is like a machine you build once and reuse forever.

  • Function = motor
  • Inputs = voltage
  • Output = rotation

What is a Function?

  • A block of code
  • Performs a specific task
  • Runs only when called

Defining & Calling a Function

def add(): print(10 + 20) add()
  • def means define
  • Code inside function does not run automatically

Function with Parameters

def add(a, b): print(a + b) add(5, 6)
  • Parameters β†’ a, b
  • Arguments β†’ 5, 6

return vs print

def add(a, b): return a + b x = add(2, 3)
  • print β†’ shows output
  • return β†’ sends value back
  • No return β†’ function returns None

Default Arguments

def greet(name="User"): print("Hello", name) greet() greet("Alex")

*args and **kwargs

def total(*args): return sum(args) def info(**kwargs): print(kwargs)
  • *args β†’ tuple
  • **kwargs β†’ dictionary

Recursion

def fact(n):  
if n == 0:
return 1
return n * fact(n-1)
  • Needs base case
  • Uses call stack
  • More memory than loops

🧠 PHASE 6: PYTHON ADVANCED

Writing less code but doing more work β€” peak engineering efficiency βš™οΈπŸš€

List Comprehension

squares = [i*i for i in range(5)]

Dictionary Comprehension

squares = {i: i*i for i in range(5)}

Lambda Functions

add = lambda a, b: a + b

map(), filter(), reduce()

nums = [1, 2, 3, 4]
list(map(lambda x: x*2, nums))
list(filter(lambda x: x%2==0, nums))

Shallow vs Deep Copy

import copy 
b = copy.copy(a)
b = copy.deepcopy(a)

Memory Reference & id()

a = [1,2]
b = a
b.append(3)

Both variables point to the same memory.

🧠 PHASE 7: OOPS IN PYTHON

(Teaching Python how the real world works)

Before OOPS, Python code feels like wires everywhere 😡 OOPS helps you build real systems β€” structured, reusable, scalable 🧱

What is OOPS?

OOPS = Object Oriented Programming System

Writing code by thinking in terms of objects, not just instructions.

  • Car
  • Student
  • Mobile
  • Bank Account
  • Properties (data)
  • Behaviors (actions)

Class & Object


Class (Blueprint)

class Student: pass

Object (Actual product)

s1 = Student()

Class β†’ circuit diagram | Object β†’ actual PCB

__init__ Method (Constructor)

class Student:  
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student("Alex", 20)
  • Runs automatically when object is created
  • Initializes object data

self Keyword

self refers to the current object.

self.name
  • Not a keyword
  • Just a convention
  • Must be first parameter

Instance vs Class Variables

class Student: college = "MIT"   # class variable
def __init__(self, name): self.name = name # instance variable
  • Instance β†’ unique for each object
  • Class β†’ shared by all objects

Methods

def show(self): print(self.name)
@staticmethod
def add(a, b): return a + b

Inheritance

class Parent: pass
class Child(Parent): pass

Child class reuses parent class features.

Polymorphism

len("Python")
len([1, 2, 3])

Same function, different behavior.

Encapsulation

self._age 
self.__salary

Data hiding β€” user sees buttons, not internal logic.

Dunder (Magic) Methods

  • __str__ β†’ print(object)
  • __len__ β†’ len(object)

🧠 PHASE 8: EXCEPTION HANDLING & FILES

Making Python robust and real-world ready 🚨

Types of Errors

  • Syntax Error
  • Runtime Error
  • Logical Error

Exception Handling

try: print(10 / 2)
except: print("Error")
else: print("No error")
finally: print("Always runs")

Custom Exception

raise ValueError("Invalid input")

File Handling

f = open("data.txt", "r")
content = f.read()
f.close()
with open("file.txt") as f: f.read()

with automatically closes the file.

Mini Project of using Next.js and Tailwind CSS