Python Notes
Python Notes
Python
Complete Notes
From your very first line of code to advanced OOP — everything
you need, in one place.
00
INTRODUCTION
What is Python?
Python is designed to be simple to read and write. Its syntax looks almost like plain English,
which is why it's the most beginner-friendly language in the world — and at the same time,
powerful enough to run Instagram, YouTube, and NASA systems.
👶 Easy to Learn
No semicolons, no curly braces, no type declarations. Just clean, readable code that looks like
English.
💪 Incredibly Powerful
Used in AI, web development, data science, automation, game dev, cybersecurity and more.
Think of it like translating an entire book from Hindi to English before giving it to
someone. The whole translation happens upfront — this is called compiling. Once
compiled, the program runs extremely fast because the computer already has the
translation ready.
🖥️ Runs!
sentence as the speaker talks. There's no pre-translation — each line is read, translated,
and executed one at a time.
📝 Source Code →
🔄 Interpreter
→ 🖥️ Runs!
(line by line)
Python is an
INTERPRETED LANGUAGE
. When you run a Python file, the Python interpreter reads your code line by line and
executes it immediately. That's why errors show up one at a time — it stops at the first
problem it hits.
Development
Speed
Slower to write & test ✅ Fast to write & test
💡 FUN FACT:
Python actually compiles your code to bytecode (.pyc files) first, then interprets that
bytecode using the Python Virtual Machine (PVM). So technically it's a bit of both —
but we call it interpreted because you never see or manage the compiled step.
🌍 Why Python? Where is it Used?
Python's simplicity and the massive ecosystem of libraries make it useful in almost every field
of technology. Here's where Python truly shines:
🤖 📊
AI & Machine Learning Data Science & Analytics
Libraries like TensorFlow, PyTorch, and scikit- Pandas, NumPy, Matplotlib — companies use
learn make Python the #1 language for AI. Python to analyse millions of rows of data and
ChatGPT, Gemini, and most modern AI tools turn them into insights and charts.
are built with Python.
🌐 ⚙️
Web Development Automation & Scripting
Django and Flask are powerful Python Automate boring tasks — rename 1000 files,
frameworks. Instagram, Pinterest, and scrape websites, send automated emails,
Spotify's backend all run on Python. schedule tasks. Python makes it simple.
🔐 🎮
Cybersecurity Game Development
Python is the go-to language for ethical Pygame lets you build 2D games with Python.
hacking and penetration testing. Tools like It's a great way to practise programming while
Metasploit and many security scripts are building something fun.
Python-based.
✨ Key Features of Python
🧹 Clean Syntax
Reads like English. Indentation is mandatory, making all Python code look consistent.
PyPI has over 400,000 packages. Whatever you want to build, there's probably already a library for it.
🌍 Cross-Platform
Write once, run anywhere — Windows, macOS, Linux. Same Python code works on all of them.
🔗 Great Community
Millions of developers, endless tutorials, Stack Overflow answers, and active forums.
🧩 Multi-Paradigm
Let's print "Hello, World!" in three different languages to see how clean Python really is:
Java
🐍 Python
print("Hello, World!")
Now that you know what Python is, where it came from, how it runs, and where it's used — let's
get it installed and write some actual code. Head to Chapter 01!
01
CHAPTER 01
Installation
Downloading Python
Open any browser → go to [Link] → download Python for your operating system.
Run the installer. This gives you the Python Virtual Machine which converts your code into
byte code that your computer can run.
⚠️ IMPORTANT
Check "Add Python to PATH" during installation on Windows — otherwise your terminal
won't find Python!
Downloading an IDE
An IDE (Integrated Development Environment) is where you write and run your code. Popular
choices are VS Code, PyCharm, and Jupyter — but we'll use VS Code throughout this book.
Setting Up VS Code
Search for and install: Python (by Microsoft) and Code Runner
02
CHAPTER 02
Comments
Comments are notes you write in your code for yourself (or other developers). Python
completely ignores them — they don't affect how the program runs.
# This is a single-line comment
"""
This is a multiline comment
written using a docstring
"""
💡 Python doesn't have a true multiline comment syntax. We "borrow" the triple-quote
string """...""" for this purpose.
Variables
Think of a variable as a labelled box — you put a value inside and refer to it by the label
whenever you need it.
name = "Akarsh"
age = 20
city = "Indore"
Naming Conventions
camelCase → myVariableName
PascalCase → MyVariableName
snake_case → my_variable_name # ✅ Python prefers this
03
CHAPTER 03
Data Types
Every value in Python has a type that tells Python what kind of data it is and what you can do
with it. You don't need to declare types — Python figures it out automatically.
int
float
complex
str
Text in quotes: "hello"
bool
NoneType
04
CHAPTER 04
Each character in a string is stored with its own Unicode number. That's why strings use more
memory than integers.
ord("A") # → 65 (Unicode of A)
chr(65) # → "A" (Character from Unicode)
String Indexing
Every character in a string has a position number called an index. Positive indexes count from
the left (starting at 0), negative from the right (starting at -1).
a = "Hello"
# H e l l o
# 0 1 2 3 4 ← positive
# -5 -4 -3 -2 -1 ← negative
print(a[0]) # H
print(a[-1]) # o
String Slicing
Slicing cuts out a piece of a string. Syntax: string[start : stop : step] — note that
stop index is excluded.
a = "hello"
print(a[1:4]) # ell (index 1,2,3 — 4 excluded)
print(a[::-1]) # olleh (reversed!)
Type Conversion
You can convert a value from one type to another using these built-in functions:
int()
→ whole number
float()
→ decimal number
str()
→ text
bool()
→ True or False
⚡ Implicit (Automatic)
a = 12
print(a / 2) # 6.0
# int ÷ int → float!
🔧 Explicit (Manual)
a = 12
a = str(a)
print(a) # "12"
Everything converts to True with bool() — except these 7 values which become False:
0 0.0 False "" [] {} ()
05
CHAPTER 05
Output — print()
name = "Akarsh"
age = 20
print("Hello!") # basic
print(f"My name is {name}") # f-string
print("Name:", name, "Age:", age) # multiple values
Input — input()
⚠️ REMEMBER:
Arithmetic Operators
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3.333…
// Floor Division 10 // 3 3
% Modulus (remainder) 10 % 3 1
** Exponentiation 2 ** 8 256
Comparison Operators
== Equal to 5 == 5 True
Logical Operators
and Both conditions are True age > 18 and has_id == True
Assignment Operators
06
CHAPTER 06
Conditional Statements
Real programs don't run the same code every time — they make decisions. Conditional
statements let your program choose what to do based on a condition. That's why they're also
if condition:
# runs when condition is True
elif another_condition:
# runs if the above was False, this is True
else:
# runs when nothing above was True
Types at a Glance
📝 Practice Questions
Q1
Q2
Q3
Q4
Accept name and age — check if the user is a valid voter (18+).
Q5
Q6 — Temperature Ladder
07
CHAPTER 07
Loops
Why Loops?
Imagine printing "Hello" 100 times. Without loops: 100 lines of code. With a loop: just 2 lines.
Transfer until bucket is empty. You don't know the count, but you know when to stop → use while.
08
CHAPTER 08
For Loop
range() generates a sequence of numbers. Think of it as saying "count from here to there".
range(stop) # 0 up to stop-1
range(start, stop) # start up to stop-1
range(start, stop, step)# start, jumping by step
list(range(5)) # [0, 1, 2, 3, 4]
list(range(1,6)) # [1, 2, 3, 4, 5]
list(range(0,10,2)) # [0, 2, 4, 6, 8]
# Output: 1 2 3 4 5
name = "hello"
Each signal = one loop iteration. Here's what each keyword does:
🛑
break
You spot an accident ahead — you immediately stop and take a U-turn. Loop ends completely.
⏭️
continue
One signal is broken — you skip it and keep driving to the next one. Loop skips this iteration.
🏠
else
You crossed all signals with no problems — you reached home safely. Runs only when loop
finishes without a break.
Q1
Q2
Input: 5 1 2 3 4 5
Q3
Input: 5 5 4 3 2 1
Q4
Q5
Input: 5 Sum = 15
Q6
Factorial of a number.
Input: 5 5! = 120
Q7
Q8
Input: 12 1 2 3 4 6 12
Q9
Q10
Check if a number is prime.
Q11
Q12
Q13
09
CHAPTER 09
While Loop
While Loop
The while loop keeps running as long as a condition is True. You use it when you don't know
how many times you'll need to repeat.
count = 1
while count <= 5:
print(count)
count += 1
# Output: 1 2 3 4 5
Always make sure your condition will eventually become False — otherwise your
program runs forever!
,
CONTINUE
, and
ELSE
Q1
Input: 1234 4 → 3 → 2 → 1
Q2
Q3
Q4
Build a number guessing game — computer picks a random number, user keeps guessing until
correct.
10
CHAPTER 10
Functions
A function is a reusable block of code with a name. Instead of writing the same logic 10 times,
def greet():
print("Hello, welcome to Python!")
📋 Parameter
greet("Alice") # ← argument
Types of Arguments
CHAPTER 11
Data Structures
11
The 4 Built-in Data Structures
When you need to store multiple values in one variable, you use a data structure. Python gives
you 4 ready to use:
12
CHAPTER 12
List
print(fruits[0]) # apple
print(fruits[-1]) # mango
print(fruits[0:2]) # ['apple', 'banana']
fruits[1] = "grape" # mutation — lists allow this!
lst = [3, 1, 4, 1, 5]
📝 List Questions
Q1
Q2
Q3
Q4
Q5
13
CHAPTER 13
Tuple
A tuple is exactly like a list, except you cannot change it once created. Use tuples for data that
should stay constant — like days of the week, coordinates, or config values.
print(days[0]) # Mon
days[0] = "X" # ❌ TypeError — tuples are immutable
14
CHAPTER 14
Set
A set automatically removes duplicates and has no guaranteed order. Great for checking
s = {1, 2, 2, 3, 3, 3}
print(s) # {1, 2, 3} — duplicates removed!
Set Operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # Union → {1,2,3,4,5,6}
a & b # Intersection → {3,4}
a - b # Difference → {1,2}
a ^ b # Symmetric diff→ {1,2,5,6}
15
CHAPTER 15
Dictionary
Key-Value Storage
A dictionary stores data as key: value pairs — like a real dictionary where you look up a word
(key) to find its meaning (value).
# Read
print(person["name"]) # Akarsh
# Update
person["age"] = 21
# Delete
del person["city"]
# Traverse
for key, val in [Link]():
print(key, "→", val)
📝 Dictionary Questions
Q1
Q2
{"a":10,"b":20,"c":30} Sum = 60
Q3
["a","b","a","c","b","a"] {"a":3,"b":2,"c":1}
Q4
16
CHAPTER 16
Exception Handling
Errors vs Exceptions
❌ Errors (unfixable)
SyntaxError — wrong syntax
✅ Exceptions (handleable!)
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
Handling Exceptions
try:
result = 10 / 0
except ZeroDivisionError:
print("Can't divide by zero!")
else:
print("Success:", result)
finally:
print("This always runs.")
Keyword Purpose
17
CHAPTER 17
File Handling
File Modes
# Writing
with open("[Link]", "w") as f:
[Link]("Hello from Python!")
# Reading
with open("[Link]", "r") as f:
content = [Link]()
print(content)
# Appending
with open("[Link]", "a") as f:
[Link]("\nAdded a new line!")
statement — it automatically closes the file for you, even if an error occurs.
18
CHAPTER 18
OOP in Python
# Functional — reusable
def add(a, b): return a + b
19
CHAPTER 19
Classes
Class = Blueprint
A class is a blueprint — like an architect's plan for a house. The plan itself isn't a house, but you
class Dog:
species = "Canis lupus" # ← Attribute
CHAPTER 20
Objects 20
Objects = Instances of a Class
🏭 Think of a
BAG FACTORY
. The factory has a blueprint (class) that needs material, zips, and pockets. Reebok
and Campus both use this blueprint but provide their own specifications — they
become two different
OBJECTS
class Bag:
def __init__(self, material, zips):
[Link] = material
[Link] = zips
print([Link]) # leather
print([Link]) # nylon
21
CHAPTER 21
Constructor
__init__ — The Constructor
The constructor is a special method that runs automatically the moment you create an object.
You use it to set up the object's initial data.
self is the object itself — it's how the method knows which object's data to set.
class Student:
def __init__(self, name, grade):
[Link] = name # stored on THIS object
[Link] = grade
s1 = Student("Akarsh", "A")
s2 = Student("Shery", "B")
print([Link]) # Akarsh
print([Link]) # Shery
22
CHAPTER 22
Attributes
Class Attribute
Instance Attribute
Methods
class Example:
count = 0
@classmethod
def class_method(cls): # needs cls
return [Link]
@staticmethod
def static_method(): # needs neither
return "Just a helper function"
23
CHAPTER 23
Inheritance
Just like children inherit traits from parents, a child class automatically gets all attributes and
class Animal:
def breathe(self):
print("Breathing...")
d = Dog()
[Link]() # inherited from Animal ✅
[Link]() # Dog's own method ✅
Types of Inheritance
24
CHAPTER 24
Polymorphism
Polymorphism = "many forms". The same method name behaves differently depending on
which object calls it.
class Dog:
def speak(self): print("Woof! 🐕")
class Cat:
def speak(self): print("Meow! 🐈")
class Duck:
def speak(self): print("Quack! 🦆")
# Same function call — different results!
for animal in [Dog(), Cat(), Duck()]:
[Link]()
🦆 DUCK TYPING:
"If it walks like a duck and quacks like a duck — it's a duck." Python doesn't care about
the type of object, only whether it has the method you're calling.
25
CHAPTER 25
Encapsulation
Encapsulation means keeping data safe inside a class and only exposing what's necessary.
Think of it like a medicine capsule — the drug is inside, protected.
class BankAccount:
def __init__(self):
[Link] = "Akarsh" # public
self._balance = 1000 # protected (convention)
self.__pin = 1234 # private (enforced)
acc = BankAccount()
print([Link]) # ✅ Akarsh
print(acc._balance) # ⚠️ works but bad practice
print(acc.__pin) # ❌ AttributeError
26
CHAPTER 26
Abstraction
Abstraction means showing only what the user needs to see, and hiding how it actually works.
Like a TV remote — you press a button, you don't need to know the electronics inside.
class Shape(ABC):
@abstractmethod
def area(self): # defined, not implemented
pass
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14 * self.r ** 2
c = Circle(5)
print([Link]()) # 78.5
27
CHAPTER 27
Dunder Methods
Magic Methods
Dunder (double underscore) methods let your objects behave like built-in Python types. They're
called automatically when you use operators or built-in functions.
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1) # (1, 2)
print(v1 + v2) # (4, 6)
print(len(v1)) # 2
28
CHAPTER 28
Advanced Topics
Decorators
A decorator wraps a function to add extra behaviour without modifying its code. Think of it as
gift wrapping — the gift (function) is still the same, but it now has a wrapper around it.
def timer(func):
def wrapper():
print("⏱ Starting...")
func()
print(" ✅ Done!")
return wrapper
@timer
def greet():
print("Hello!")
greet()
# ⏱ Starting...
# Hello!
# ✅ Done!
When you don't know how many arguments a function will receive, use *args (for positional)
print(total(1, 2, 3, 4)) # 10
print(total(10, 20)) # 30
Comprehensions — One-liners
# List comprehension
squares = [x**2 for x in range(5)] # [0,1,4,9,16]
evens = [x for x in range(10) if x%2==0] # [0,2,4,6,8]
# Dict comprehension
squared = {x: x**2 for x in range(5)} # {0:0,1:1,2:4...}
# Set comprehension
unique = {x%3 for x in range(10)} # {0,1,2}
Lambda Functions
print(square(5)) # 25
print(add(3, 7)) # 10
print(check(4)) # even
map(), filter(), zip()
nums = [1, 2, 3, 4, 5]
# Built-in modules
import math
import random
from datetime import datetime
print([Link](16)) # 4.0
print([Link](1, 100)) # random number
print([Link]()) # current date/time
Pattern 2
Pattern 3
Q1 — Strong Number
Q2 — Prime Range
Input: 10, 30 11 13 17 19 23 29
Q3 — Most Frequent
A M E S S A G E F R O M T H E C R E AT O R
"We'll be learning all of this and so much more on this channel. I, Akarsh
sincerely thank each and every one of you who stayed with us till the