PYTHON NOTES
Definition of Python
• Python is a high-level, interpreted, object-oriented,
general-purpose programming language developed
by Guido van Rossum in 1989 and released in 1991.
• It is known for its simple, English-like syntax,
extensive libraries, and versatility, which makes it
widely used in areas like web development, data
science, artificial intelligence, automation, and
education.
Key points in definition:
• High-level → Easy to understand, close to human
language.
• Interpreted → Executes code line by line (no
compilation needed).
• Object-Oriented → Supports classes, objects,
inheritance, polymorphism.
• General-purpose → Can be used in almost every
domain (not limited to one field).
Father of Python
• Guido van Rossum is the father (creator) of Python.
• He developed Python in 1989 at Centrum Wiskunde
& Informatica (CWI) in the Netherlands.
• The first public release was in 1991.
• He is often called “Benevolent Dictator For Life
(BDFL)” of Python until he stepped down in 2018.
Why the name "Python"?
• The name Python does not come from the snake 🐍.
• Guido was a fan of a British comedy TV show "Monty
Python's Flying Circus".
• He wanted a short, unique, and catchy name → so he
named the language Python.
Python History
• 1980s: Guido worked on a project called ABC language. It was
simple but had limitations.
• 1989: He started working on Python during Christmas
holidays.
• 1991: First official release → Python 0.9.0 (with functions,
exception handling, core data types).
• 2000: Release of Python 2.0 (list comprehensions, garbage
collection).
• 2008: Release of Python 3.0 (major changes, not backward-
compatible).
• 2010 onward: Python 2 and 3 were maintained separately.
• 2020: Python 2 officially retired.
• Now: Python 3.x is the main version used everywhere.
Python Versions
• Python 1.0 – 1994 (basic features, exception
handling).
• Python 2.0 – 2000 (list comprehensions, garbage
collection).
• Python 3.0 – 2008 (print function, Unicode, better
libraries).
• Latest stable (2025) → Python 3.13 is available.
Features of Python
✅ Simple & easy to learn – syntax like English.
✅ Interpreted – runs line by line (no compilation
needed).
✅ Open-source & free – anyone can use/modify.
✅ Portable – runs on Windows, Mac, Linux.
✅ Object-Oriented & Functional – supports multiple
programming paradigms.
✅ Extensive libraries – NumPy, Pandas, Django,
TensorFlow, etc.
✅ Dynamic typing – no need to declare variable types.
✅ High-level language – hides low-level complexity.
✅ Huge community support – millions of developers
worldwide.
Applications of Python
• Web development – Django, Flask.
• Data Science & AI/ML – Pandas, NumPy, TensorFlow, Scikit-
learn.
• Automation & Scripting – repetitive tasks automation.
• Software development – GUI apps, desktop apps.
• Cybersecurity & Networking – penetration testing,
automation.
• Game development – Pygame.
• IoT & Embedded systems – Raspberry Pi, MicroPython.
• Education – beginners learn Python first due to simplicity.
Install Python
1. Download Python
Open your browser and go to the official website:
🔗 [Link]
You’ll see the latest Python version (example: Python
3.13.x).
Click Download Python 3.x.x (Windows installer).
2. Run the Installer
Locate the downloaded file (usually in Downloads
folder).
Double-click the installer ([Link]).
3. Important Step – Add to PATH
In the installation window:
✅ Check the box “Add Python 3.x to PATH”
(very important).
Then click Install Now.
4. Wait for Installation
The installer will set up Python and pip (Python
package manager).
Once complete, you’ll see a success message.
5. Verify Installation
Open Command Prompt (cmd).
Type:
python --version
or
python -V
✅ It should display the installed version (e.g.,
Python 3.13.0).
Tokens in Python
Tokens are the smallest building blocks of a Python program.
Types of tokens:
Keywords → reserved words (if, else, for, while, class, def, etc.).
Identifiers → names for variables, functions, classes (age,
sumOfNumbers).
Literals → constant values (10, 3.14, 'hello', True, None).
Operators → +, -, *, /, //, %, **, ==, !=, etc.
Punctuators / Separators → (), {}, [], ,, :, . etc.
Comments → # single line, ''' multi line '''.
Keywords
• Keywords are the reserved words in Python
that have special meaning and purpose.
How to display all keywords
Import keyword
Print([Link])
Then display the all keywords in python.
Key Points about Keywords
• They are case-sensitive (e.g., True ≠ true).
• They cannot be redefined as variables.
• Python has 35+ keywords (varies slightly with
versions).
Note: cannot be used as identifiers (variable
names, function names, etc.).
Variables
• A variable in Python is a named memory location
used to store data.
• It acts as a container for holding values, which can
change during program execution.
Example:
x = 10 # here, x is a variable storing integer 10
name = "Bhavani" # name is a variable storing a string
Rules for Naming Variables in Python
1. A variable name must start with a letter or underscore (_).
2. Example: age = 20, _total = 100
3. The rest of the name can contain letters, digits, or
underscores.
4. Example: student1 = "Ram"
5. Variable names are case-sensitive.
6. Example: Age and age are different variables.
7. Variables can be of any length.
8. Python does not require type declaration (dynamic typing).
Literals (Constants)
Fixed values assigned to identifiers.
Types:
Numeric Literals → 10, 3.14, 5+7j
String Literals → "Python", 'AI'
Boolean Literals → True, False
Special Literal → None
Example:
x = 100 # integer literal
pi = 3.14 # float literal
name = "Python" # string literal
flag = True # boolean literal
data = None # special literal
Punctuators (Delimiters / Symbols)
Special symbols used to define structure.
Examples:
Parentheses → ()
Brackets → []
Braces → {}
Colon → :
Comma → ,
Dot → .
Example:
list1 = [1, 2, 3]
dict1 = {"a": 10, "b": 20}
Comments
Notes in the program ignored by Python
interpreter.
Types:
Single-line → # This is a comment
Multi-line →
""" This is a multi-line comment """
Input and Output Statements
Input Statement
• Input statements are used to take data from the
user during program execution.
• In Python, we use the input() function for this.
Syntax:
variable = input("Message for user")
By default, input() takes data as a string.
If needed, we convert it into int, float, etc.
Example 1: Taking String Input
name = input("Enter your name: ") print("Hello", name)
Output:
Enter your name: Bhavani Hello Bhavani
Example 2: Taking Integer Input
age = int(input("Enter your age: "))
print("Your age is", age)
Output:
Enter your age: 20
Your age is 20
Example 3: Taking Multiple Inputs
a, b = map(int, input("Enter two numbers:
").split())
print("Sum =", a + b)
Output:
Enter two numbers: 10 20
Sum = 30
Output Statement
• Output statements are used to display results on the
screen.
• In Python, we use the print() function.
Syntax:
print(object(s), sep=' ', end='\n')
• sep → separator between values (default space " ").
• end → what to print at end (default newline \n).
Example 1: Simple Print
print("Welcome to Python")
Output:
Welcome to Python
Example 2: Printing Variables
name = "Bhavani"
age = 20
print("Name:", name, "Age:", age)
Output:
Name: Bhavani
Age: 20
Example 3: Using sep and end
print("A", "B", "C", sep="-", end=" END")
Output:
A-B-C END
Example 4: Formatted Output (f-strings)
a, b = 10, 20
print(f"Sum of {a} and {b} is {a+b}")
Output:
Sum of 10 and 20 is 30
Operators in Python Programmingu
• Operators are symbols that perform operations on
variables and values.
• The values on which operators act are called
operands.
Example:
a = 10
b=5
print(a + b) # '+' is operator, a & b are operands
Types of Operators in Python
1. Arithmetic Operators
Used for basic mathematical calculations.
Operator Description Example Output
+ Addition 10 + 5 15
- Subtraction 10 – 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2.0
% Modulus (remainder)10 % 3 1
** Exponent (power) 2 ** 3 8
// Floor Division 10 // 3 3
Example:
a, b = 10, 3
print(a + b) # 13
print(a ** b) # 1000
2. Relational (Comparison) Operators
Used to compare values → result is True/False.
Operator Description Example Output
== Equal to 10 == 5 False
!= Not equal 10 != 5 True
> Greater than 10 > 5 True
< Less than 10 < 5 False
>= Greater or equal 10 >= 5 True
<= Less or equal 10 <= 5 False
Example:
x, y = 7, 10
print(x < y) # True
print(x == y) # False
3. Logical Operators
• Used to combine conditions.
Operator Description Example Output
and True if both are True (5 > 2 and 10 > 3) True
or True if at least one is True (5 > 10 or 10 > 3) True
not Reverses result not(5 > 2) False
Example:
a, b = True, False
print(a and b) # False
print(a or b) # True
print(not a) # False
4. Assignment Operators
Used to assign values to variables.
Operator Example Equivalent To
= x=5 Assign 5 to x
+= x += 3 x=x+3
-= x -= 3 x=x–3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
**= x **= 2 x = x ** 2
//= x //= 2 x = x // 2
Example:
x = 10
x += 5
print(x) # 15
5. Bitwise Operators
Work on binary (bit-level) values.
Operator Description Example (a=5, b=3) Result
& AND 5 & 3 → 0101 & 0011 1
| OR 5|3
^ XOR 5^3 6
~ NOT (1’s complement) ~5 -6
<< Left Shift 5 << 1 10
>> Right Shift 5 >> 1 2
6. Membership Operators
Check if a value exists in a sequence.
Operator Example Output
In "a" in "apple“ True
not in "z" not in "apple“ True
Example:
name = "python"
print("p" in name) # True
print("z" not in name) # True
7. Identity Operators
Check if two objects are same (memory address).
Operator Example Output
Is x is y True if same object
is not x is not y True if different
Example:
a = [1, 2, 3]
b=a
c = [1, 2, 3]
print(a is b) # True (same reference)
print(a is c) # False (different objects, same values)
DATA TYPES
1) What is a data type?
• A data type tells Python what kind of value a
variable holds and what operations are allowed on
that value.
• Python is dynamically typed (you don’t declare
types) and strongly typed (types are enforced).
• You can check a value’s type with type() and test with
isinstance().
x = 10
print(type(x)) # <class 'int'>
print(isinstance(x, int)) # True
2) Main built-in data type categories (step-by-step)
A. Numeric types
int — integers (… -2, -1, 0, 1, 2 …)
Example:
a = 42
float — decimal numbers
Example: b = 3.14
complex — real + imaginary (x + yj)
Example: c = 2 + 3j
a=5
b = 2.5
c = 1 + 2j
Print(type(a)) <class int>
Print(type(b)) <class float>
Print(type(c)) <class complex>
B. Sequence types (ordered collections)
str (string) — text, immutable.
Example:
s = "hello“
Indexing: s[0], slicing: s[1:4]
list — ordered, mutable collection.
Example:
L = [1, 2, 3] → you can
[Link](4) or L[0] = 10
tuple — ordered, immutable collection.
Example:
T = (1, 2, 3)
Example:-
s = "Python"
L = [10, 20, 30]
T = (10, 20, 30)
Print(type(s)) # <class str>
Print(type(L)) # <class list>
Print(type(T)) # <class tuple>
C. Mapping type
dict (dictionary)
key → value pairs, unordered (in concept; insertion
order preserved in recent Python).
Example:
d = {"name":"Bhavani", "roll":101}
Print(d)
Print(type(d))
D. Set types
set — unordered, mutable, unique elements.
Example:
S = {1,2,3}
Ops: union (|), intersection (&), add/remove
frozenset — immutable set.
S = {1,2,2,3} # becomes {1,2,3}
[Link](4)
E. Boolean
bool — True or False. (Subtype of int.)
Example:
flag = True
Often used in conditions: if flag: ...
Conditional Statements in Python
• Conditional statements are used in Python to make
decisions in a program.
• They allow the program to execute certain blocks of
code only if a condition is True, otherwise execute
another block.
The main conditional statements are:
1. if
2. if-else
3. if-elif-else
4. nested if
5. switch (using match-case / dictionary)
1. if Statement
The if statement is used to test a condition.
If the condition is True, the block of code
executes; otherwise, it is skipped.
Syntax
if condition:
# block of code
Example program
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
2. if-else Statement
The if-else statement provides two paths.
If the condition is True, one block executes;
otherwise, the else block executes.
Syntax
if condition:
# block 1
else:
# block 2
Example program
age = 18
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
Output:
Eligible to vote
3. if-elif-else Statement
• The if-elif-else statement is used when we have multiple conditions.
• First if is checked.
• If false, elif conditions are checked one by one.
• If all are false, else executes.
Syntax
if condition1:
# block 1
elif condition2:
# block 2
elif condition3:
# block 3
else:
# block 4
Example program
marks = 72
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: Fail")
Output:
Grade: B
4. Nested if Statement
A nested if means an if statement inside
another if statement.
Syntax
if condition1:
if condition2:
# block of code
Example Program
num = 20
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
else:
print("Positive Odd Number")
else:
print("Negative Number")
Output:
Positive Even Number
5. Switch Statement (Alternative in Python)
Python does not have a direct switch statement
like C/Java.
Instead, we use dictionary mapping or match-
case (introduced in Python 3.10).
Method 2: Using match-case (Python 3.10+)
day = 5
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
case _:
print("Invalid day")
Output:
Friday
Loops in Python
• A loop in Python is used to execute a block of code
repeatedly as long as a condition is true or until the sequence is
exhausted.
• Loops help in reducing code repetition.
Types of Loops in Python
Python mainly has 3 types of loops:
1. for loop
2. while loop
3. nested loops
• (Along with these, we use break, continue, and pass for loop
control.)
for loop in Python
• The for loop in Python is used to iterate over a
sequence (like list, tuple, string, dictionary, or range).
• It executes the block of code once for each item in
the sequence.
1. for loop with Sequence
2. for loop with range() function
1. for loop with Sequence
• A sequence in Python is an ordered collection of
items (list, tuple, string).
• The for loop picks elements one by one from the
sequence.
Syntax:
for var in sequence:
block of code
Example:1
For loop with List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example: 2
For loop with String
for ch in "PYTHON":
print(ch)
Output:
P
Y
T
H
O
N
EXAMPLE : 3
For loop with Tuple
numbers = (10, 20, 30)
for num in numbers:
print(num)
Output:
10
20
30
2. for loop with range() function
• The range() function generates a sequence of
numbers.
• It is commonly used with for loops.
Syntax
range(start, stop, step)
start → (optional) starting number (default = 0)
stop → ending number (not included)
step → (optional) difference between numbers (default =
1)
Example:1
Simple range
for i in range(5):
print(i)
Output:
0
1
2
3
4
EXAMPLE : 2
Range with start and stop
for i in range(2, 7):
print(i)
Output:
2
3
4
5
6
EXAMPLE : 3
Range with step
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
while loop in Python
• The while loop in Python is used to execute a block
of code repeatedly as long as a given condition is
True.
• 👉 Once the condition becomes False, the loop stops.
• It is often used when the number of iterations is not
known in advance.
Syntax
while condition:
# block of code
• condition → Expression that returns True/False.
• The block keeps running while the condition is True.
• When the condition becomes False, the loop ends.
Example : 1
1. Simple while loop
count = 1
while count <= 5:
print("Count =", count)
count += 1
Output:
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
2. While loop with decrement
num = 5
while num > 0:
print(num)
num -= 1
Output:
5
4
3
2
1
Nested Loops in Python
• A nested loop means a loop inside another loop.
• The outer loop runs first, and for each iteration of
the outer loop, the inner loop runs completely.
• They are useful for working with tables, patterns,
matrices, and multi-dimensional data.
Syntax
for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# block of code
(or with while loop)
while condition1:
while condition2:
# block of code
Example : 1
1. Nested for loop
for i in range(3): # outer loop
for j in range(2): # inner loop
print("i =", i, "j =", j)
Output:
i=0j=0
i=0j=1
i=1j=0
i=1j=1
i=2j=0
i=2j=1
EXAMPLE : 2
2. Multiplication Table using nested loop
for i in range(1, 4): # rows
for j in range(1, 6): # columns
print(i * j, end="\t")
print()
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
3. Pattern Printing (Star Triangle)
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print("*", end=" ")
print()
Output:
*
**
***
****
*****
Strings in Python
Definition
• A string in Python is a sequence of characters
enclosed in single quotes ('), double quotes
("), or triple quotes (''' or """).
• Strings are immutable → once created, they
cannot be changed.
Example
str1 = 'Hello'
str2 = "Python“
str3 = '''This is a multi-line string.'''
print(str1)
print(str2)
print(str3)
Output:
Hello
Python
This is a multi-line string.
String Operations
Python provides many operations we can perform on
strings.
1. Concatenation (Joining strings)
a = "Hello"
b = "World"
print(a + " " + b)
Output:
Hello World
2. Repetition
-- to repeate the string
msg = "Hi "
print(msg * 3)
Output:
Hi Hi Hi
3. Indexing
👉 Access individual characters using index (0-
based).
text = "Python"
print(text[0]) # first character
print(text[-1]) # last character
Output:
P
n
4. Slicing
👉 Extract part of a string using [start:end:step].
word = "Programming"
print(word[0:6]) # from index 0 to 5
print(word[3:]) # from index 3 to end
print(word[:5]) # from start to index 4
print(word[::2]) # every 2nd character
Output:
Progra
gramming
Progr
Pormig
5. Membership Operators
-- to check the given element in a string or not
msg = "Python Programming"
print("Python" in msg)
print("Java" not in msg)
Output:
True
True
Common String Methods
upper() --- Converts to uppercase
lower() -- Converts to lowercase
title() -- Converts to title case
capitalize() -- First letter capitalized
strip() -- Removes spaces from both sides
replace(a, b) -- Replaces substring
split() -- Splits string into list
join() -- Joins list into string
find() -- Returns first index of substring
count() -- Counts occurrences
startswith() -- Checks prefix
endswith() -- Checks suffix
isalnum() -- True if all chars are alphanumeric
isalpha() -- True if all chars are alphabets
isdigit() -- True if all chars are digits
List in Python
• A list in Python is an ordered, mutable (changeable), and
heterogeneous collection of elements.
• Elements are written inside square brackets [] separated by
commas.
• Lists can store integers, floats, strings, or even other lists.
Example
my_list = [10, 20, 30, "Python", 3.14]
print(my_list)
Output:
[10, 20, 30, 'Python', 3.14]
List Operations
1. Indexing
nums = [10, 20, 30, 40]
print(nums[0]) # first element
print(nums[-1]) # last element
Output:
10
40
2. Slicing
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # from index 1 to 3
print(nums[:3]) # first three elements
print(nums[::2]) # every second element
Output:
[20, 30, 40]
[10, 20, 30]
[10, 30, 50]
3. Concatenation
-- to combine two or more lists
a = [1, 2, 3]
b = [4, 5]
print(a + b)
Output:
[1, 2, 3, 4, 5]
4. Repetition
-- to repeat the list elements.
nums = [1, 2]
print(nums * 3)
Output:
[1, 2, 1, 2, 1, 2]
5. Membership
-- to check the given element in a list or not
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)
print("mango" not in fruits)
Output:
True
True
Common List Methods
append(x) -- Adds element at end
insert(i, x) -- Inserts at index I
extend(lst2) -- Adds multiple elements
remove(x) -- Removes first occurrence
pop(i) -- Removes element at index
clear() -- Removes all elements
index(x) -- Returns index of element
count(x) -- Counts occurrences
sort() -- Sorts list ascending
reverse() -- Reverses list order
copy() -- Returns shallow copy
Examples
1. Adding and Removing
numbers = [10, 20, 30]
[Link](40)
[Link](20)
print(numbers)
Output:
[10, 30, 40]
2. Sorting
nums = [5, 1, 4, 2, 3]
[Link]()
print(nums)
Output:
[1, 2, 3, 4, 5]
3. Nested List
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[0][1]) # element at row 0, col 1
Output:
2
TUPLE
• A tuple is an ordered, immutable collection of items
in Python.
• Ordered: items have a fixed index (0, 1, 2...).
• Immutable: once created, you cannot change
elements (no item assignment).
• Tuples can store mixed data types and allow
duplicates.
Creating tuples (step-by-step)
Literal (parentheses)
t = (1, 2, 3)
Without parentheses (comma-separated)
t = 4, 5, 6 # still a tuple
Single-element tuple — needs a comma
t1 = (7,) # tuple
t2 = (7) # integer, NOT a tuple
Empty tuple
empty = ()
Using constructor
t = tuple([1,2,3]) # from list
t = tuple("abc") # -> ('a','b','c')
Operations
Indexing — get element by position
t = (10, 20, 30)
t[0] # → 10
t[-1] # → 30
Explanation: positive indices from left, negative
from right.
Slicing — get subtuple
t = (0,1,2,3,4)
t[1:4] # → (1, 2, 3)
t[:3] # → (0, 1, 2)
t[::2] # → (0, 2, 4)
Concatenation (+) — join tuples
a = (1,2)
b = (3,4)
a+b # → (1, 2, 3, 4)
Repetition (*) — repeat elements
(1,2) * 3 # → (1, 2, 1, 2, 1, 2)
Membership test (in)
3 in (1,2,3) # → True
5 in (1,2,3) # → False
Length, min, max, sum (for numeric tuples)
t = (4,1,7)
len(t) # → 3
min(t) # → 1
max(t) # → 7
sum(t) # → 12
Iteration
for x in (10,20,30):
print(x) # prints 10 then 20 then 30
Indexing nested tuples
t = (1, (2, 3), 4)
t[1] # → (2, 3)
t[1][0] # → 2
Slicing + step
t = (0,1,2,3,4,5)
t[1:5:2] # → (1, 3)
Conversion to/from list (to modify)
t = (1,2,3)
lst = list(t)
lst[0] = 100
t2 = tuple(lst) # → (100, 2, 3)
Tuple packing & unpacking (very useful)
Packing — put values into a tuple automatically
t = 1, 2, 3 # packing
Unpacking — assign tuple contents to variables
a, b, c = (10, 20, 30) # a=10, b=20, c=30
Extended unpacking
a, *rest = (1,2,3,4)
# a=1, rest=[2,3,4]
# note: rest is a list
Swap variables using tuple unpacking
a, b = 1, 2
a, b = b, a # swap
Tuple methods
count(x) — number of occurrences
t = (1,2,2,3)
[Link](2) #→2
index(x) — first index of x (ValueError if not
present)
t = (10,20,30)
[Link](20) #→1
[Link](99) #raises ValueError
set
Definition
• A set is an unordered, mutable collection of
unique, hashable items.
• Unordered: no index, no guaranteed order.
• Unique: duplicates are removed
automatically.
• Mutable: you can add/remove elements (but
elements themselves must be hashable —
e.g., numbers, strings, tuples).
1) Creating sets — step by step
Empty set — use set() (NOT {} because {} makes an
empty dict)
s = set()
print(s) # -> set()
From iterable (list, tuple, string):
s = set([1,2,2,3])
print(s) # -> {1, 2, 3}
s2 = set("hello")
print(s2) # -> {'o','h','e','l'}
# order may differ
Literal (non-empty) — braces with items:
s = {1, 2, 3}
Set comprehension:
s = {x*x for x in range(6)}
print(s) # -> {0, 1, 4, 9, 16, 25}
Key properties (quick)
• No indexing: s[0] → TypeError.
• No duplicates: set([1,1,2]) → {1,2}.
• Elements must be hashable — 1, "a", (1,2) ok;
[1] or {'a':1} not allowed (unhashable).
• Membership test is fast: x in s is on average
O(1).
Basic operations
Membership test
s = {1,2,3}
print(2 in s) # -> True
print(5 in s) # -> False
Add element (in-place) — add()
s = {1,2}
[Link](3)
print(s) # -> {1,2,3}
Update with multiple elements (in-place) — update()
accepts any iterable
[Link]([4,5])
print(s) # -> {1,2,3,4,5}
Remove element
remove(x) — raises KeyError if not present.
discard(x) — does nothing if x not present.
s = {1,2,3}
[Link](2) # s -> {1,3}
[Link](9) # KeyError
[Link](9) # no error
pop() — remove & return an arbitrary element (because set is
unordered)
s = {10,20,30}
v = [Link]()
print(v, s) # v is some element; s has the rest
Clear — remove all elements
[Link]()
print(s) # -> set()
Copy (shallow)
s = {1,2,3}
c = [Link]()
print(c) # -> {1,2,3}
Mathematical set operations (two forms: operator
& method)
Let A = {1,2,3,4}, B = {3,4,5,6}.
Union — combine elements
Operator: A | B
Method: [Link](B)
A = {1,2,3,4}
B = {3,4,5,6}
print(A | B) # -> {1,2,3,4,5,6}
print([Link](B)) # -> {1,2,3,4,5,6}
Intersection — elements common to both
Operator: A & B
Method: [Link](B)
Let A = {1,2,3,4}, B = {3,4,5,6}.
print(A & B) # -> {3,4}
print([Link](B)) # -> {3,4}
Difference — items in A not in B
Operator: A – B
Method: [Link](B)
Let A = {1,2,3,4}, B = {3,4,5,6}.
print(A - B) # -> {1,2}
print([Link](B)) # -> {1,2}
Symmetric difference — items in A or B but not
both
Operator: A ^ B
Method: A.symmetric_difference(B)
Let A = {1,2,3,4}, B = {3,4,5,6}.
print(A ^ B) # -> {1,2,5,6}
Set relation tests
A = {1,2}
B = {1,2,3}
print([Link](B)) # -> True (A ⊆ B)
print([Link](A)) # -> True (B ⊇ A)
print([Link]({3,4})) # -> True if no
common elements
Immutable set — frozenset
frozenset is an immutable set — can be used as
dict key or inside another set (because it's
hashable).
fs = frozenset([1,2,3])
d = {fs: "value"}
print(d) # -> {frozenset({1,2,3}): 'value'}
[Link](4) #would raise AttributeError
DICTONARIES
What is a dictionary?
1. A dictionary is an unordered, mutable collection of key
→ value pairs.
2. Keys are unique and usually immutable (strings, numbers,
tuples).
3. Values can be any object.
1) Create dictionaries (step-by-step)
# 1. Empty dict
d1 = {}
d2 = dict()
print(d1, d2) # => {} {}
# 2. Literal with initial values
grades = {'Alice': 85, 'Bob': 92}
print(grades) # => {'Alice': 85, 'Bob': 92}
# 3. From sequence of pairs
pairs = dict([('x', 10), ('y', 20)])
print(pairs) # => {'x': 10, 'y': 20}
# 4. fromkeys (creates keys with same value)
dk = [Link](['a','b'], 0)
print(dk) # => {'a': 0, 'b': 0}
# 5. Comprehension
squares = {i: i*i for i in range(4)}
print(squares) # => {0: 0, 1: 1, 2: 4, 3: 9}
Access values
d = {'name': 'Aisha', 'age': 20}
# 1. Square-bracket (KeyError if missing)
print(d['name']) # => 'Aisha'
print(d['city']) # KeyError
# 2. get() (safe)
print([Link]('city')) # => None
print([Link]('city', 'Unknown')) # => 'Unknown'
[] raises KeyError if key missing;
get() returns None (or provided default).
3) Add & update items
d = {'a': 1, 'b': 2}
# 1. Add / update by assignment
d['c'] = 3 # add
d['b'] = 20 # update
print(d) # => {'a':1, 'b':20, 'c':3}
# 2. update() to merge another dict or pairs
[Link]({'d':4, 'b':99})
print(d) # => {'a':1, 'b':99, 'c':3, 'd':4}
Remove items
d = {'a':1, 'b':2, 'c':3} # del
del d['a']
print(d) # => {'b':2, 'c':3}
pop: returns removed value or default
v = [Link]('b')
print(v, d) # => 2 {'c':3}
pop with default (no error if key missing)
v2 = [Link]('no', 'not found')
print(v2) # => 'not found'
#popitem: removes and returns last inserted pair
(tuple)
pair = [Link]()
print(pair, d) # => ('c', 3) {}
clear: empty the dict
d = {'x':1}
[Link]()
print(d) # => {}
Common operations & iteration
d = {'a': 1, 'b': 2, 'c': 3}
membership (keys)
print('a' in d) # => True
print(1 in d) # => False (checks keys)
length
d = {'a': 1, 'b': 2, 'c': 3}
print(len(d)) # => 3
iterate keys
d = {'a': 1, 'b': 2, 'c': 3}
for k in d:
print(k) #abc
iterate key-value pairs
d = {'a': 1, 'b': 2, 'c': 3}
for k, v in [Link]():
print(k, v) #a1 b2 c3
views (live): keys(), values(), items()
d = {'a': 1, 'b': 2, 'c': 3}
ks = [Link]()
print(ks) # => dict_keys([a','b','c'])
d['d'] = 4
print(list(ks)) # now includes 'd' (views are dynamic)
Important dict methods
• [Link]() — remove all items.
• [Link]() — shallow copy.
• [Link](seq[, value]) — create new dict from keys.
• [Link](key[, default]) — safe read (no KeyError).
• [Link]() — view of (key, value) pairs.
• [Link]() — view of keys.
• [Link]() — view of values.
• [Link](key[, default]) — remove & return value.
• [Link]() — remove & return last inserted pair.
• [Link](key[, default]) — return value, set default
if missing.
• [Link]([other]) — merge another dict or iterable of
pairs.
• dict.__contains__(key) / key in dict — membership.
• [Link](), [Link](), [Link]() are live views —
reflect future changes.
FUNCTIONS
• A function in Python is a block of reusable
code that performs a specific task.
• It can take inputs (parameters), execute
statements, and optionally return a value.
👉 Functions help to:
• Avoid code repetition
• Make code modular and easy to read
• Allow reusability
General syntax:
def function_name(parameters):
"""Optional docstring"""
# statements
return value # optional
Types of Functions in Python
1. Built-in Functions
• Functions already provided by Python.
• You can use them directly without defining.
Examples: print(), len(), sum(), max(), type()
2. User-defined Functions
Functions created by the programmer using def.
Example:
def greet(name):
return f"Hello, {name}"
3. Anonymous Functions
(Lambda Functions)
• Functions without a name, defined using
lambda keyword.
• Used for small, single-expression operations.
Example:
square = lambda x: x*x
print(square(5)) # 25
4. Recursive Functions
• A function that calls itself directly or indirectly.
• Useful for problems like factorial, Fibonacci, tree
traversal.
Example:
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
5. Higher-Order Functions
• Functions that take other functions as arguments or
return a function.
Examples: map(), filter(), reduce()
Example:
def apply_twice(f, x):
return f(f(x))
def add_one(n):
return n+1
print(apply_twice(add_one, 5)) #7
Sample Program: Calculate Square
and Cube of a Number
# Function to calculate square
def square(num):
return num * num
# Function to calculate cube
def cube(num):
return num * num * num
# Main program
n = int(input("Enter a number: "))
print("Square of", n, "is:", square(n))
print("Cube of", n, "is:", cube(n))
Types of Functions Based on Parameters &
Return Values
• In Python, functions can be classified into 4
types:
• 1⃣ Function without parameters and without
return value
• Does not take input (no parameters)
• Does not return anything (returns None by
default)
Example:
def greet():
print("Hello, Welcome to Python Programming!")
greet() # Function call
Output:
Hello, Welcome to Python Programming!
2. Function with parameters and without return value
• Takes input (parameters)
• Performs task but does not return value
Example:
def greet(name):
print("Hello,", name, "Welcome to Python Programming!") # Function call
greet("Asha")
greet("Ravi")
Output:
Hello, Asha Welcome to Python Programming!
Hello, Ravi Welcome to Python Programming!
3. Function without parameters but with return value
• Does not take input
• Returns a value to the caller
Example:
def pi_value():
return 3.14159 # Function call
result = pi_value()
print("The value of pi is:", result)
Output:
The value of pi is: 3.14159
4. Function with parameters and with return value
• Takes input (parameters)
• Returns a value after computation
Example:
def add(a, b):
return a + b # Function call
sum1 = add(5, 10)
sum2 = add(20, 30)
print("Sum1:", sum1) print("Sum2:", sum2)
Output:
Sum1: 15
Sum2: 50
Recursion in Python
Definition:
Recursion is a process in which a function calls itself
directly or indirectly.
👉 Every recursive function must have:
Base case – condition to stop recursion
Recursive case – function calls itself with
smaller/simpler input
Factorial using Recursion
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n-1)
# Main program
num = int(input("Enter a number: "))
print("Factorial of", num, "is:", factorial(num))
Fibonacci using Recursion
def fibonacci(n):
# Base cases
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
else:
return fibonacci(n-1) + fibonacci(n-2)
# Main program
terms = int(input("Enter number of terms: "))
print("Fibonacci series:")
for i in range(terms):
print(fibonacci(i), end=" ")
Anonymous Function (Lambda) in
Python
• An anonymous function in Python is a function that does not
have a name.
• It is created using the lambda keyword.
• That’s why it is also called a lambda function.
• It can have any number of arguments but only one
expression.
• The result of the expression is automatically returned.
Syntax:
lambda arguments : expression
Examples
1. Simple addition using lambda
add = lambda a, b: a + b
print(add(5, 3)) # Output: 8
2. Square of a number
square = lambda x: x * x
print(square(6)) # Output: 36
3. Check even or odd
even_odd = lambda n: "Even" if n % 2 == 0 else "Odd“
print(even_odd(10)) # Output: Even
print(even_odd(7)) # Output: Odd
Key Points to Remember:
1. lambda functions are one-line functions.
2. They are mostly used with map(), filter(), reduce().
3. They cannot have multiple statements.
4. They are useful when you need a short, throwaway
function.
map() in Python
• The map() function in Python is used to apply a function to
each element of an iterable (like list, tuple, etc.).
• It returns a map object (which is an iterator).
• To get the final result, we usually convert it into a list, tuple,
or set.
Syntax:
map(function, iterable)
1. function → a function (normal or lambda) that performs an
operation.
2. iterable → sequence like list, tuple, or string.
Examples
1. Square each number
numbers = [1, 2, 3, 4, 5] # using normal function
def square(x):
return x * x
result = list(map(square, numbers))
print(result) # Output: [1, 4, 9, 16, 25]
2. Square each number using lambda
numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x ** 2, numbers))
print(result) # Output: [1, 4, 9, 16, 25]
3. Convert list of strings to uppercase
names = ["python", "java", "c"]
result = list(map([Link], names))
print(result) # Output: ['PYTHON', 'JAVA', 'C']
4. Convert integers to strings
numbers = [10, 20, 30]
result = list(map(str, numbers))
print(result) # Output: ['10', '20', '30']
Key Points to Remember:
1. map() works faster than using a loop for transformation.
2. Can be combined with lambda functions for short
operations.
3. Returns an iterator object (must convert to list/tuple to view
results).
filter() in Python
1. The filter() function in Python is used to filter elements
from an iterable (list, tuple, etc.) based on a condition.
2. It applies a function (that returns True or False) to each
element of the iterable.
3. Only those elements for which the function returns True are
included in the result.
4. It returns a filter object (an iterator).
Syntax:
filter(function, iterable)
function → a function that returns True or False.
iterable → sequence (list, tuple, set, etc.).
Examples
1. Filter even numbers
numbers = [1, 2, 3, 4, 5, 6]
def is_even(n):
return n % 2 == 0
result = list(filter(is_even, numbers))
print(result) # Output: [2, 4, 6]
2. Using lambda for even numbers
numbers = [1, 2, 3, 4, 5, 6]
result = list(filter(lambda n: n % 2 == 0, numbers))
print(result) # Output: [2, 4, 6]
3. Filter names starting with 'A‘
names = ["Alice", "Bob", "Anil", "David", "Arjun"]
result = list(filter(lambda name: [Link]("A"), names))
print(result) # Output: ['Alice', 'Anil', 'Arjun']
5. Filter vowels from a string
string = "python programming"
vowels = list(filter(lambda ch: ch in "aeiou", string))
print(vowels) # Output: ['o', 'o', 'a', 'i']
✅ Key Points to Remember:
• filter() is used for selection (filtering), while map() is
used for transformation.
• Returns an iterator object → need to convert into list
or tuple.
• Often used with lambda functions for short
conditions.
reduce() in Python
• The reduce() function is used to apply a function
cumulatively to all elements of an iterable (like list,
tuple, etc.).
• It keeps reducing the iterable into a single value by
applying the function one by one.
• It is not a built-in function directly in Python, it is
available in the functools module.
Syntax:
• from functools import reduce reduce(function,
iterable[, initializer])
• function → a function that takes two arguments.
• iterable → sequence (list, tuple, etc.).
• initializer (optional) → a starting value (if given, it is
used before iterable elements).
Examples
1. Sum of all numbers
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda a, b: a + b, numbers)
print(result) # Output: 15
👉 Works like (((1+2)+3)+4)+5 = 15
2. Product of all numbers
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda a, b: a * b, numbers)
print(result) # Output: 120
3. Find maximum number in a list
from functools import reduce
numbers = [10, 25, 7, 99, 56]
result = reduce(lambda a, b: a if a > b else b, numbers)
print(result) # Output: 99
Files in Python Programming
Definition of a File
• A file is a collection of data stored on a
computer’s storage device (like HDD, SSD).
Files are used to store data permanently for
future use.
• Python provides built-in functions to create,
read, write, and delete files.
Modes in File Handling:
Mode Meaning
"r“ Read (default).
Opens file for reading. Error if file does not exist.
"w“ Write.
Creates new file or overwrites existing file.
"a“ Append.
Adds data to end of file without overwriting.
"x“ Exclusive creation.
Fails if file already exists.
"t“ Text mode (default).
"b“ Binary mode
(for images, videos, etc.).
"r+“ Read + Write mode.
1. File Operations in Python
• Python uses a built-in function open() to work
with files.
Syntax:
file_object = open("filename", "mode")
2. Opening and Closing Files
Example 1: Open and Close File
f = open("[Link]", "w") # open file in write mode
[Link]("Hello, Python File Handling!")
[Link]() # close file
• 👉 Here, a new file [Link] is created and text
is written.
3. Writing to a File
Example 2:
f = open("[Link]", "w")
[Link]("Python makes file handling easy!\n")
[Link]("This is the second line.\n")
[Link]()
✅ If [Link] exists → content will be overwritten.
✅ If not → new file will be created.
4. Appending to a File
Example 3:
f = open("[Link]", "a") # append mode
[Link]("This line is appended at the end.\n")
[Link]()
• 👉 Appends new data instead of replacing old
content.
5. Reading from a File
Example 4: Read Entire File
f = open("[Link]", "r")
content = [Link]() # reads entire file
print(content)
[Link]()
Example 5: Read Line by Line
f = open("[Link]", "r")
for line in f:
print(line, end="") # prints line by line
[Link]()
6. Using with Statement
• Best practice in Python is to use with → it
automatically closes the file.
Example 6:
with open("[Link]", "r") as f:
print([Link]())
• 👉 No need to call close().
7. File Methods
Method Description
read(size) Reads size bytes. If no size,
reads entire file.
readline() Reads one line.
readlines() Reads all lines into a list.
write(str) Writes a string to file.
writelines(list) Writes list of strings.
close() Closes the file.
8. Example: Writing & Reading
# Writing
with open("[Link]", "w") as f:
[Link]("Name: Bhavani\n") [Link]("Course: [Link]\n")
# Reading
with open("[Link]", "r") as f:
data = [Link]()
print(data)
✅ Output:
Name: Bhavani Course: [Link]
9. Working with Binary Files
• For images, audio, video → "rb" and "wb" modes.
Example 7:
# Copy an image
with open("[Link]", "rb") as f1:
with open("copy_photo.jpg", "wb") as f2:
[Link]([Link]())
Summary
• Files store data permanently.
• Python uses open() function with different modes (r,
w, a, rb, etc.).
• Use with statement to manage files safely.
• Common operations: read, write, append, close.
OOPS
(Object-Oriented Programming)
1. OOP (Object-Oriented Programming) in Python is a
programming paradigm that organizes code into classes and
objects.
2. A class is a blueprint (template) that defines the attributes
(data) and methods (functions).
3. An object is an instance of a class, which represents real-
world entities.
4. OOP in Python helps to achieve modularity, reusability,
abstraction, and security by using concepts like class, object,
constructor, encapsulation, inheritance, polymorphism, and
abstraction.
CLASS
• A class in Python is a blueprint (template)
used to create objects.
• It bundles attributes (variables/data) and
methods (functions/behavior) into a single
unit.
• A class does not hold actual data itself —
instead, objects created from the class store
real values.
Basic Example – Student Class
class student:
name = ‘surya’ # attributes
rno = 101 # attributes
def read(): # method
print(‘reading’)
def write(): # method
print(‘writing’)
OBJECT
• An object in Python is an instance of a class.
• When a class is defined, no memory is allocated.
• When an object is created from that class, memory is
allocated and the object stores actual data.
• Objects allow us to access the attributes (variables)
and methods (functions) defined inside the class.
👉 In short:
“Object = real-world entity created from a class
blueprint.”
Example Program
class student:
name = ‘surya’ # attributes
rno = 101 # attributes
def read(): # method
print(‘reading’)
def write(): # method
print(‘writing’)
S1 = student()
S2 = student()
Here s1,s2 are objects
Example : Using constructor & self
class Student:
def __init__(self, name, roll): # constructor
[Link] = name # attribute
[Link] = roll # attribute
def display(self):
print(f"Name: {[Link]}, Roll: {[Link]}")
s1 = Student("Anita", 101)
s2 = Student("Rahul", 102)
[Link]()
[Link]()
SELF
• In Python, self is a reference to the current object (instance)
of a class.
• It is used inside class methods to access the attributes and
methods of that specific object.
• When you call a method on an object, Python automatically
passes the object itself as the first argument → by convention,
this argument is named self.
👉 In short:
“self represents the instance of the class through which a
method or attribute is accessed.”
Example 1 — Using self to access attributes
class Student:
def __init__(self, name, roll):
[Link] = name # self binds attribute to object
[Link] = roll
def display(self): # self refers to current object
print(f"Name: {[Link]}, Roll: {[Link]}")
s1 = Student("Anita", 101)
s2 = Student("Rahul", 102)
[Link]() # self = s1
[Link]() # self = s2
Output
Name: Anita, Roll: 101
Name: Rahul, Roll: 102
CONSTRUCTOR
• A constructor is a special method in a class that is
automatically called when a new object is created.
• In Python, the constructor method is always named __init__.
• Its main purpose is to initialize the object’s attributes with
given values at the time of creation.
👉 In short:
“Constructor in Python is a special method __init__ used to
initialize the data of an object automatically when it is
created.”
Example 1 — Simple Constructor
class Student:
def __init__(self, name, roll): # constructor
[Link] = name
[Link] = roll
def display(self):
print(f"Name: {[Link]}, Roll: {[Link]}")
s1 = Student("Anita", 101)
s2 = Student("Rahul", 102)
[Link]()
[Link]()
Output
Name: Anita, Roll: 101
Name: Rahul, Roll: 102
Instance vs Class Variables
• Instance variable — unique to each object
(self.x).
• Class variable — shared across all instances
(declared in class body).
EXAMPLE:
class Dog:
species = "Canis familiaris" # class variable
def __init__(self, name):
[Link] = name # instance variable
d1 = Dog("Rex")
d2 = Dog("Bella")
print([Link], [Link])
Inheritance
• Inheritance in Python is a feature of Object-Oriented
Programming (OOP) that allows a class (called child
class or derived class) to reuse the properties and
methods of another class (called parent class or
base class).
• 👉 It helps in code reusability, extensibility, and
makes programming easier to manage.
syntax
class ParentClass:
# parent class members
pass
class ChildClass(ParentClass):
# child class members
pass
Types of Inheritance in Python
(i) Single Inheritance
A child class inherits from only one parent class.
✅ Example:
class Parent:
def display(self):
print("This is the Parent class.")
class Child(Parent):
def show(self):
print("This is the Child class.")
c = Child()
[Link]() # inherited from Parent
[Link]() # own method
(ii) Multiple Inheritance
A child class inherits from more than one parent class.
✅ Example:
class Father:
def father_info(self):
print("Father's class.")
class Mother:
def mother_info(self):
print("Mother's class.")
class Child(Father, Mother):
def child_info(self):
print("Child's class.")
c = Child()
c.father_info()
c.mother_info()
c.child_info()
(iii) Multilevel Inheritance
Inheritance across multiple levels
(grandparent → parent → child).
✅ Example:
class Grandparent:
def grandparent_info(self):
print("This is the Grandparent.")
class Parent(Grandparent):
def parent_info(self):
print("This is the Parent.")
class Child(Parent):
def child_info(self):
print("This is the Child.")
c = Child()
c.grandparent_info()
c.parent_info()
c.child_info()
(iv) Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
✅ Example:
class Parent:
def display(self):
print("This is the Parent class.")
class Child1(Parent):
def show1(self):
print("This is Child1.")
class Child2(Parent):
def show2(self):
print("This is Child2.")
c1 = Child1()
[Link]()
c1.show1()
c2 = Child2()
[Link]()
c2.show2()
(v) Hybrid Inheritance
A combination of two or more types of inheritance.
✅ Example:
class A:
def method_A(self):
print("Class A method")
class B(A):
def method_B(self):
print("Class B method")
class C(A):
def method_C(self):
print("Class C method")
class D(B, C):
def method_D(self):
print("Class D method")
d = D()
d.method_A()
d.method_B()
d.method_C()
d.method_D()
The super() Function
The super() function is used in inheritance to call a method
from the parent class.
✅ Example:
class Parent:
def display(self):
print("This is the Parent class.")
class Child(Parent):
def display(self):
super().display() # calling parent method
print("This is the Child class.")
c = Child()
[Link]()
Advantages of Inheritance
1. Code reusability
2. Reduces redundancy
3. Improves readability & maintainability
4. Supports extensibility
Polymorphism
Polymorphism is an Object-Oriented Programming
(OOP) concept where the same function, operator,
or object behaves differently in different situations.
👉 The word Polymorphism means "many forms".
It allows us to use a common interface for different
data types or classes.
1. Operator Overloading
Operator overloading allows us to use
operators (+, -, *, etc.) with user-defined
objects (classes).
In Python, operators are implemented using
special methods (also called magic methods,
like __add__, __sub__, __mul__, etc.).
Example program:
class Student:
def __init__(self, marks):
[Link] = marks
# Overloading "+" operator
def __add__(self, other):
return [Link] + [Link]
s1 = Student(50)
s2 = Student(70)
print("Total Marks:", s1 + s2) # Uses __add__()
Output:
Total Marks: 120
2. Method Overloading
Method overloading means defining multiple
methods with the same name but different
arguments.
👉 In Python, true method overloading is not
supported (like in Java or C++).
But we can achieve it by using default arguments
or *args.
Example: Method Overloading
(using default arguments)
class Math:
def add(self, a, b=0, c=0):
return a + b + c
m = Math()
print([Link](10, 20)) # 30
print([Link](10, 20, 30)) # 60
3. Method Overriding
Method overriding happens when a child
class provides a specific implementation of a
method that is already defined in its parent
class.
👉 Here, the child class method overrides the
parent class method.
Example: Method Overriding
class Animal:
def sound(self):
print("This is an animal sound.")
class Dog(Animal):
def sound(self): # Overriding parent method
print("Dog barks.")
class Cat(Animal):
def sound(self): # Overriding parent method
print("Cat meows.")
a1 = Dog()
a2 = Cat()
[Link]() # Dog barks.
[Link]() # Cat meows.
Encapsulation
Encapsulation is an Object-Oriented Programming (OOP)
concept that refers to wrapping up data (variables) and
methods (functions) into a single unit (class).
👉 It helps in data hiding and data security by controlling
access to variables and methods.
In Python, encapsulation is implemented using:
1. Public members → accessible anywhere
2. Protected members → accessible within the class and
subclasses (prefix _)
3. Private members → accessible only within the class (prefix
__)
Syntax
class ClassName:
def __init__(self):
self.public_var = value # public
self._protected_var = value # protected
self.__private_var = value # private
Types of Encapsulation in Python
(i) Public Members
Variables and methods defined without any underscore.
✅ Example:
class Student:
def __init__(self, name):
[Link] = name # public variable
s = Student("Bhavani")
print("Student Name:", [Link]) # accessible anywhere
(ii) Protected Members
• Variables and methods prefixed with a single underscore _.
• They can be accessed outside the class but are considered protected (not
recommended).
✅ Example:
class Student:
def __init__(self, name, roll):
self._roll = roll # protected variable
[Link] = name
class Marks(Student):
def display(self):
print("Name:", [Link])
print("Roll:", self._roll)
m = Marks("Bhavani", 101)
[Link]()
print(m._roll) # still accessible, but not recommended
(iii) Private Members
• Variables and methods prefixed with double underscore __.
• They cannot be accessed directly from outside the class.
✅ Example:
class Student:
def __init__(self, name, marks):
self.__marks = marks # private variable
[Link] = name
def display(self):
print("Name:", [Link])
print("Marks:", self.__marks)
s = Student("Bhavani", 95)
[Link]()
# print(s.__marks) ❌ Error: private variable
Advantages of Encapsulation
• Provides data security (hides sensitive data)
• Prevents unauthorized access
• Improves code maintainability
• Flexible (control data using getters & setters)
Abstraction
• Abstraction is an Object-Oriented Programming (OOP)
concept that hides internal implementation details and only
shows the essential features to the user.
• 👉 In simple words: “Show what is necessary, hide the
complexity.”
• For example, when you use a mobile phone, you press
buttons to call or send messages but you don’t know the
internal circuits working behind it.
• In Python, abstraction is achieved using abstract classes and
abstract methods (from the abc module).
Abstract Class
• An abstract class is a class that cannot be
instantiated (we cannot create objects directly).
• It is used as a blueprint for other classes.
• It may contain one or more abstract methods.
Abstract Method
• A method that is declared but not implemented in
the abstract class.
• The child class must override/implement the
abstract method.
• Defined using @abstractmethod decorator from the
abc module.
Syntax
from abc import ABC, abstractmethod
class AbstractClass(ABC): # Inheriting ABC class
@abstractmethod
def method(self):
pass # only declared, not implemented
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle):
def start(self):
print("Car has started.")
def stop(self):
print("Car has stopped.")
class Bike(Vehicle):
def start(self):
print("Bike has started.")
def stop(self):
print("Bike has stopped.")
# v = Vehicle() ❌ Error: Cannot create object of abstract class
c = Car()
b = Bike()
[Link]()
[Link]()
[Link]()
[Link]()
Output:
Car has started.
Car has stopped.
Bike has started.
Bike has stopped.
Advantages of Abstraction
• Hides complex implementation
• Increases security (only essential details are
exposed)
• Makes code more flexible & maintainable
• Helps in achieving loose coupling