Python Interview
Python Interview
Since this is placement preparation, I'll teach you only what matters for interviews and writing good Python code—not
unnecessary theory.
Python Introduction
What is Python?
Python is a high-level, interpreted, general-purpose, object-oriented programming language created by Guido van Rossum and
first released in 1991.
It is widely used in:
• Web Development
• Machine Learning
• Artificial Intelligence
• Data Science
• Automation & Scripting
• Cybersecurity
• Cloud Computing
Features of Python
These are common interview questions.
1. Simple & Easy to Learn
Python has a clean and readable syntax.
Java
[Link]("Hello World");
Python
print("Hello World")
2. Interpreted Language
Python code is executed line by line.
Unlike Java:
Java
Source Code
↓
Compiler
↓
Bytecode
↓
JVM
↓
Output
Python:
Source Code
↓
Interpreter
↓
Output
Advantage
• Easier debugging
• Faster development
3. Dynamically Typed
You don't declare variable types.
x = 10
x = "Hello"
x = 5.5
The same variable can store different data types.
4. Object-Oriented
Everything in Python is an object.
Supports:
• Classes
• Objects
• Inheritance
• Polymorphism
• Encapsulation
• Abstraction
5. Platform Independent
A Python program written on Windows can run on:
• Linux
• macOS
without changing the code (assuming the required Python version and dependencies are available).
7. Open Source
Python is free to use and has a large community.
Python Versions
Current projects generally use Python 3.x. Python 2 reached end of life in 2020, so you only need to learn Python 3.
Running Python
Interactive Mode
>>> 5 + 5
10
Used for quick testing.
Script Mode
Create a file:
[Link]
Run:
python [Link]
Advantages
• Easy syntax
• Huge ecosystem
• Cross-platform
• Fast development
• Large community
• Great for AI/ML
Disadvantages
• Slower than C/C++
• Higher memory usage
• Global Interpreter Lock (GIL) limits true multithreading for CPU-bound tasks
Interview Questions
Be ready to answer these:
1. Who created Python?
Guido van Rossum
6. What is PEP 8?
PEP 8 (Python Enhancement Proposal 8) is the official style guide for writing readable Python code.
Quick Revision
High-Level Language
Interpreted
Dynamically Typed
Object-Oriented
General Purpose
Cross-Platform
Open Source
Huge Standard Library
Next Topic
We'll move to Variables & Data Types, where you'll learn:
• Variables
• Naming rules
• Primitive data types
• type()
• id()
• Mutable vs Immutable (very common interview question)
• Memory management basics
• Type conversion
This is one of the most important Python topics for placements.
Perfect! Since this is placement preparation, I'll teach you only what matters for interviews and writing good Python code—not
unnecessary theory.
Python Introduction
What is Python?
Python is a high-level, interpreted, general-purpose, object-oriented programming language created by Guido van Rossum and
first released in 1991.
It is widely used in:
• Web Development
• Machine Learning
• Artificial Intelligence
• Data Science
• Automation & Scripting
• Cybersecurity
• Cloud Computing
Features of Python
These are common interview questions.
1. Simple & Easy to Learn
Python has a clean and readable syntax.
Java
[Link]("Hello World");
Python
print("Hello World")
2. Interpreted Language
Python code is executed line by line.
Unlike Java:
Java
Source Code
↓
Compiler
↓
Bytecode
↓
JVM
↓
Output
Python:
Source Code
↓
Interpreter
↓
Output
Advantage
• Easier debugging
• Faster development
3. Dynamically Typed
You don't declare variable types.
x = 10
x = "Hello"
x = 5.5
The same variable can store different data types.
4. Object-Oriented
Everything in Python is an object.
Supports:
• Classes
• Objects
• Inheritance
• Polymorphism
• Encapsulation
• Abstraction
5. Platform Independent
A Python program written on Windows can run on:
• Linux
• macOS
without changing the code (assuming the required Python version and dependencies are available).
7. Open Source
Python is free to use and has a large community.
Python Versions
Current projects generally use Python 3.x. Python 2 reached end of life in 2020, so you only need to learn Python 3.
Running Python
Interactive Mode
>>> 5 + 5
10
Used for quick testing.
Script Mode
Create a file:
[Link]
Run:
python [Link]
Advantages
• Easy syntax
• Huge ecosystem
• Cross-platform
• Fast development
• Large community
• Great for AI/ML
Disadvantages
• Slower than C/C++
• Higher memory usage
• Global Interpreter Lock (GIL) limits true multithreading for CPU-bound tasks
Interview Questions
Be ready to answer these:
1. Who created Python?
Guido van Rossum
6. What is PEP 8?
PEP 8 (Python Enhancement Proposal 8) is the official style guide for writing readable Python code.
Quick Revision
High-Level Language
Interpreted
Dynamically Typed
Object-Oriented
General Purpose
Cross-Platform
Open Source
Huge Standard Library
Next Topic
We'll move to Variables & Data Types, where you'll learn:
• Variables
• Naming rules
• Primitive data types
• type()
• id()
• Mutable vs Immutable (very common interview question)
• Memory management basics
• Type conversion
This is one of the most important Python topics for placements.
Output
Python uses the print() function to display output.
Syntax
print(object)
Example 1
print("Hello World")
Output
Hello World
Example 2
print(10)
print(20.5)
print(True)
Output
10
20.5
True
print() can display different data types.
print(name, age)
Output
Bhargavi 21
By default, print() separates values with a space.
sep Parameter
Changes the separator between values.
print("2026", "07", "15", sep="-")
Output
2026-07-15
Another example:
print("Python", "Java", "C++", sep=" | ")
Output
Python | Java | C++
end Parameter
By default:
print("Hello")
print("World")
Output:
Hello
World
Because end="\n" (new line) is the default.
Change it:
print("Hello", end=" ")
print("World")
Output:
Hello World
Input
Python uses the input() function.
Syntax
variable = input("Message")
Example:
name = input("Enter your name: ")
print(name)
Input
Bhargavi
Output
Bhargavi
print(age)
print(type(age))
Input:
21
Output:
21
<class 'str'>
Converting Input
Suppose you write:
a = input("Enter first number: ")
b = input("Enter second number: ")
print(a + b)
Input:
10
20
Output:
1020
Why?
Because Python concatenates two strings.
Correct way:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a + b)
Output:
30
Float
salary = float(input("Enter salary: "))
String
name = input("Enter name: ")
Boolean
There's no direct boolean input.
flag = input("Enter True or False: ")
print(flag)
print(a)
print(b)
Input:
10 20
print(a + b)
Input:
10 20
Output:
30
How does this work?
input()
Returns:
"10 20"
.split()
Converts it to:
["10", "20"]
map(int, ...)
Converts each string to an integer:
10, 20
Finally:
a = 10
b = 20
Common Mistakes
Forgetting that input() returns a string.
age = input()
print(age + 5)
This raises a TypeError.
Correct:
age = int(input())
print(age + 5)
Interview Questions
1. Which function is used to display output?
Answer: print()
2. Which function is used to take input?
Answer: input()
3. What does input() return?
Answer: A string.
4. What is the purpose of sep?
Answer: It specifies the separator between multiple values in print().
5. What is the purpose of end?
Answer: It specifies what is printed after the output. By default, it's a newline (\n).
Practice Questions
1. Print your name, age, and college on one line.
2. Take a user's name and print:
3. Hello, <name>!
4. Take two integers as input and print their sum.
5. Take three numbers in one line and print their average.
6. Print:
7. Python -> Java -> C++
using sep.
8. Print "Hello" and "World" on the same line using end.
Summary
• print() → Displays output.
• input() → Takes user input.
• input() always returns a string.
• Use int(), float(), etc., to convert input to the required type.
• sep changes the separator.
• end changes what is printed after the output.
This topic is straightforward but frequently tested because interviewers often check whether you know that input() returns a
string by default.
Excellent! You're getting the syntax right. Just a couple of small fixes.
5. Print
Python -> Java -> C++
Use the sep parameter.
Try:
print("Python", "Java", "C++", sep=" -> ")
Output:
Python -> Java -> C++
Placement Tip
Remember these three patterns—they come up everywhere:
Single input
name = input()
Integer input
n = int(input())
Multiple integer input
a, b = map(int, input().split())
If you master these, you'll be comfortable with almost every basic input pattern in Python.
Score: (9.5/10)
The only mistake was the missing quote in the f-string. Otherwise, you're on the right track.
Next topic: Variables & Data Types (one of the most important Python topics for placements).
Awesome! This is one of the most important topics for Python interviews.
Variables & Data Types
What is a Variable?
A variable is a name that refers to a value stored in memory.
name = "Bhargavi"
age = 21
cgpa = 9.35
Here:
• name, age, cgpa → Variables
• "Bhargavi", 21, 9.35 → Values
Variable Declaration
Unlike Java:
int age = 21;
Python:
age = 21
No need to specify the data type.
Dynamic Typing
Python is dynamically typed.
x = 10
print(type(x))
Output:
<class 'int'>
Now:
x = "Hello"
print(type(x))
Output:
<class 'str'>
The same variable can hold different data types.
Naming Rules
Valid
name = "Bhargavi"
_age = 21
cgpa2 = 9.35
student_name = "ABC"
Invalid
2name = "abc" # Starts with a number
class = 10 # Keyword
Multiple Assignment
a = b = c = 10
print(a)
print(b)
print(c)
Output:
10
10
10
Another way:
a, b, c = 10, 20, 30
print(a, b, c)
Output:
10 20 30
Swapping
Python's most famous feature.
Java:
temp = a;
a = b;
b = temp;
Python:
a = 10
b = 20
a, b = b, a
print(a, b)
Output:
20 10
No temporary variable needed.
Data Types
Python has many data types.
The main built-in ones are:
Data Type Example
int 10
float 3.14
complex 2+3j
bool True
str "Python"
list [1,2,3]
tuple (1,2,3)
set {1,2,3}
dict {"name":"Bhargavi"}
NoneType None
int
age = 21
print(type(age))
Output:
<class 'int'>
float
pi = 3.14159
print(type(pi))
Output:
<class 'float'>
complex
Python supports complex numbers.
x = 3 + 4j
print(type(x))
Output:
<class 'complex'>
Mostly used in scientific computing.
bool
Only two values.
True
False
Example:
is_pass = True
print(type(is_pass))
Output:
<class 'bool'>
str
name = "Bhargavi"
or
name = 'Bhargavi'
Both are valid.
None
Represents no value.
x = None
print(type(x))
Output:
<class 'NoneType'>
type()
Returns the data type.
a = 100
print(type(a))
Output:
<class 'int'>
id()
Returns the memory identity (unique identifier) of an object.
a = 10
print(id(a))
Output:
140457823912720
The exact number changes every run.
Example:
a = 10
b=a
print(id(a))
print(id(b))
Initially, both refer to the same object, so they typically have the same id.
isinstance()
Checks whether an object belongs to a given type.
a = 10
print(isinstance(a, int))
Output:
True
Another example:
print(isinstance("Hello", str))
Output:
True
Type Conversion
Implicit Conversion
Python converts automatically when safe.
a = 10
b = 2.5
print(a + b)
Output:
12.5
The int is automatically converted to float.
Explicit Conversion
You convert the type yourself.
age = "21"
print(int(age))
Output:
21
Examples:
int("10")
float("10")
str(100)
bool(1)
list("abc")
tuple([1,2,3])
set([1,2,2,3])
Outputs:
10
10.0
'100'
True
['a', 'b', 'c']
(1, 2, 3)
{1, 2, 3}
4. What is None?
A special object representing the absence of a value.
Practice Questions
1. Create variables for your name, age, and CGPA, then print their types.
2. Swap two numbers without using a third variable.
3. Convert "250" to an integer and multiply it by 2.
4. Convert 150 to a string and print its type.
5. Check whether 9.35 is a float using isinstance().
6. Predict the output:
a = 10
b = 10.0
print(type(a))
print(type(b))
print(a + b)
Your Turn
Solve the 6 practice questions without looking back. I'll review your answers like an interviewer and point out any mistakes or
improvements.
1. Create variables for your name, age, and CGPA, then print their types.
name = "Bhargavi"
age = 21
cgpa = 9.35
print(type(name))
print(type(age))
print(type(cgpa))
Output
<class 'str'>
<class 'int'>
<class 'float'>
a, b = b, a
print(a, b)
Output
20 10
num = int(num)
print(num * 2)
Output
500
num = str(num)
print(type(num))
Output
<class 'str'>
print(type(a))
print(type(b))
print(a + b)
Output
<class 'int'>
<class 'float'>
20.0
Operators in Python
Operators are symbols used to perform operations on variables and values.
1. Arithmetic Operators
Operator Meaning Example Output
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5 * 3 15
/ Division 5/2 2.5
// Floor Division 5 // 2 2
% Modulus 5%2 1
** Exponent 5 ** 2 25
Example:
a = 10
b=3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
Output
13
7
30
3.3333333333333335
3
1
1000
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
Output
False
True
False
True
False
True
3. Assignment Operators
Operator Example Same As
= a=5 Assign
+= a += 2 a=a+2
-= a -= 2 a=a-2
*= a *= 2 a=a*2
/= a /= 2 a=a/2
//= a //= 2 a = a // 2
%= a %= 2 a=a%2
**= a **= 2 a = a ** 2
Example:
a = 10
a += 5
print(a)
a *= 2
print(a)
Output
15
30
4. Logical Operators
Operator Meaning
and Both True
or At least one True
not Opposite
Example:
a = 10
b = 20
print(a is b)
print(a is c)
print(a == c)
Output
True
False
True
Interview Question:
• == compares values
• is compares object identity (memory reference)
6. Membership Operators
Checks whether an element exists in a sequence.
Operator Meaning
in Present
not in Not Present
Example:
name = "Bhargavi"
print("B" in name)
print("z" in name)
print("z" not in name)
Output
True
False
True
7. Bitwise Operators
Operator Meaning
& AND
` `
^ XOR
~ NOT
<< Left Shift
>> Right Shift
Example:
a=5
b=3
print(a & b)
print(a | b)
print(a ^ b)
Output
1
7
6
(Bitwise operators are less common unless you're interviewing for systems or low-level programming roles.)
print(a == b)
print(a is b)
Output
True
False
Practice Questions
1.
print(15 // 4)
2.
print(2 ** 5)
3.
a=5
a += 10
print(a)
4.
print(True and False)
5.
print("a" in "Bhargavi")
6.
a = [1, 2]
b=a
print(a is b)
print(a == b)
These operators (especially arithmetic, comparison, logical, assignment, identity, and membership) are the ones most frequently
asked in Python interviews.
Strings
A string is a sequence of characters enclosed in quotes.
name = "Bhargavi"
college = 'VVCE'
Both single (' ') and double (" ") quotes are valid.
Creating Strings
s1 = "Python"
s2 = 'Python'
s3 = """Hello
World"""
Triple quotes are used for multi-line strings.
print(s[0])
print(s[2])
print(s[5])
Output
P
t
n
Negative Indexing
P y t h o n
-6 -5 -4 -3 -2 -1
s = "Python"
print(s[-1])
print(s[-2])
Output
n
o
Slicing
Syntax
string[start:end:step]
• start → included
• end → excluded
Example
s = "Python"
print(s[0:4])
print(s[2:5])
print(s[:3])
print(s[3:])
print(s[:])
Output
Pyth
tho
Pyt
hon
Python
Step in Slicing
s = "Python"
print(s[::2])
print(s[::-1])
Output
Pto
nohtyP
[::-1] is the easiest way to reverse a string.
String is Immutable
You cannot modify a character.
s = "Python"
s[0] = "J"
Output
TypeError
Correct:
s = "Python"
s = "J" + s[1:]
print(s)
Output
Jython
String Concatenation
a = "Hello"
b = "World"
Repetition
print("Hi" * 3)
Output
HiHiHi
Length
s = "Python"
print(len(s))
Output
6
Lower
print("PYTHON".lower())
Output
python
Title
print("hello world".title())
Output
Hello World
Capitalize
print("python".capitalize())
Output
Python
Strip
print(" hello ".strip())
Output
hello
Replace
print("banana".replace("a", "o"))
Output
bonono
Count
print("banana".count("a"))
Output
3
Find
print("banana".find("n"))
Output
2
Returns -1 if not found.
Index
print("banana".index("n"))
Output
2
Unlike find(), index() raises an error if the substring is not found.
Startswith
print("Python".startswith("Py"))
Output
True
Endswith
print("Python".endswith("on"))
Output
True
Split
s = "apple banana mango"
print([Link]())
Output
['apple', 'banana', 'mango']
Join
words = ["I", "love", "Python"]
print(" ".join(words))
Output
I love Python
Membership
print("Py" in "Python")
print("Java" in "Python")
Output
True
False
Comparison
print("abc" == "abc")
print("abc" < "abd")
Output
True
True
Strings are compared lexicographically (dictionary order).
Reverse a String
s = "Python"
print(s[::-1])
Output
nohtyP
Practice Questions
1. Print the first and last character of "Placement".
2. Reverse "Python" using slicing.
3. Count the number of 'a' characters in "banana".
4. Replace "Java" with "Python" in "I love Java".
5. Split "one,two,three" using ,.
6. Join ["AI", "ML", "Python"] with "-".
Once you're comfortable with strings, we'll move to Lists, which is the next major topic and one of the most frequently used data
structures in Python.
print(s[0])
print(s[-1])
Output
P
t
print(s[::-1])
Output
nohtyP
print([Link]("a"))
Output
3
print([Link]("Java", "Python"))
Output
I love Python
print([Link](","))
Output
['one', 'two', 'three']
print("-".join(words))
Output
AI-ML-Python
Next topic: Lists (the most important Python data structure for placements).
Lists
A list is an ordered, mutable (changeable) collection that can store duplicate and different data types.
nums = [10, 20, 30]
Creating Lists
a = [1, 2, 3]
b = ["Python", "Java"]
d = []
Properties of Lists
• Ordered
• Mutable
• Allows Duplicates
• Stores Different Data Types
Indexing
nums = [10, 20, 30, 40]
print(nums[0])
print(nums[2])
print(nums[-1])
Output
10
30
40
Slicing
nums = [10,20,30,40,50]
print(nums[1:4])
print(nums[:3])
print(nums[2:])
print(nums[::-1])
Output
[20, 30, 40]
[10, 20, 30]
[30, 40, 50]
[50, 40, 30, 20, 10]
Updating List
nums = [10,20,30]
nums[1] = 100
print(nums)
Output
[10, 100, 30]
Unlike strings, lists are mutable.
Adding Elements
append()
Adds one element at the end.
nums = [1,2,3]
[Link](4)
print(nums)
Output
[1, 2, 3, 4]
insert()
nums = [1,2,3]
[Link](1,100)
print(nums)
Output
[1, 100, 2, 3]
extend()
Adds another iterable.
a = [1,2]
b = [3,4]
[Link](b)
print(a)
Output
[1, 2, 3, 4]
Removing Elements
remove()
Removes first occurrence of value.
nums = [1,2,3,2]
[Link](2)
print(nums)
Output
[1, 3, 2]
pop()
Removes by index.
nums = [10,20,30]
[Link]()
print(nums)
Output
[10, 20]
[Link](0)
print(nums)
Output
[20]
del
nums = [10,20,30]
del nums[1]
print(nums)
Output
[10, 30]
clear()
nums = [1,2,3]
[Link]()
print(nums)
Output
[]
Searching
index()
nums = [10,20,30]
print([Link](20))
Output
1
count()
nums = [1,2,2,2,3]
print([Link](2))
Output
3
Sorting
nums = [5,2,8,1]
[Link]()
print(nums)
Output
[1, 2, 5, 8]
Descending
[Link](reverse=True)
print(nums)
Output
[8, 5, 2, 1]
sorted()
Doesn't modify original list.
nums = [5,2,8,1]
print(sorted(nums))
print(nums)
Output
[1, 2, 5, 8]
[5, 2, 8, 1]
Reverse
nums = [1,2,3]
[Link]()
print(nums)
Output
[3, 2, 1]
Copy
a = [1,2,3]
b = [Link]()
print(b)
Output
[1, 2, 3]
Length
nums = [10,20,30]
print(len(nums))
Output
3
Membership
nums = [10,20,30]
print(20 in nums)
print(100 in nums)
Output
True
False
List Concatenation
a = [1,2]
b = [3,4]
print(a+b)
Output
[1,2,3,4]
List Repetition
print([1,2]*3)
Output
[1,2,1,2,1,2]
Nested Lists
matrix = [
[1,2],
[3,4]
]
print(matrix[1][0])
Output
3
List Comprehension
nums = [x*x for x in range(5)]
print(nums)
Output
[0,1,4,9,16]
Even numbers
even = [x for x in range(10) if x%2==0]
print(even)
Output
[0,2,4,6,8]
print(a)
Output
[1,2,[3,4]]
a = [1,2]
[Link]([3,4])
print(a)
Output
[1,2,3,4]
Practice Questions
1.
nums = [10,20,30]
[Link](40)
print(nums)
2.
nums = [10,20,30]
[Link](1,15)
print(nums)
3.
nums = [1,2,3,4]
[Link](2)
print(nums)
4.
nums = [5,2,8,1]
print(sorted(nums))
5.
nums = [1,2,2,3,2]
print([Link](2))
6.
nums = [1,2,3]
print(nums[::-1])
7.
nums = [10,20,30]
print(20 in nums)
8.
nums = [x for x in range(1,6)]
print(nums)
Tuples
A tuple is an ordered, immutable collection that allows duplicate values.
t = (10, 20, 30)
Properties
• Ordered
• Immutable (Cannot be modified)
• Allows Duplicates
• Supports Different Data Types
Creating Tuples
t1 = (1, 2, 3)
t2 = ("Python", "Java")
t4 = ()
print(type(t))
Output
<class 'int'>
Correct:
t = (10,)
print(type(t))
Output
<class 'tuple'>
Remember: A comma makes it a tuple.
Indexing
t = (10,20,30,40)
print(t[0])
print(t[2])
print(t[-1])
Output
10
30
40
Slicing
t = (10,20,30,40,50)
print(t[1:4])
print(t[:3])
print(t[2:])
print(t[::-1])
Output
(20, 30, 40)
(10, 20, 30)
(30, 40, 50)
(50, 40, 30, 20, 10)
Immutability
t = (10,20,30)
t[1] = 100
Output
TypeError
You cannot modify a tuple.
Tuple Packing
t = 10, 20, 30
print(t)
Output
(10, 20, 30)
Tuple Unpacking
a, b, c = (10,20,30)
print(a)
print(b)
print(c)
Output
10
20
30
Length
t = (10,20,30)
print(len(t))
Output
3
Count
t = (1,2,2,3,2)
print([Link](2))
Output
3
Index
t = (10,20,30)
print([Link](20))
Output
1
Membership
t = (10,20,30)
print(20 in t)
print(100 in t)
Output
True
False
Concatenation
a = (1,2)
b = (3,4)
print(a+b)
Output
(1, 2, 3, 4)
Repetition
print((1,2)*3)
Output
(1, 2, 1, 2, 1, 2)
Conversions
List → Tuple
lst = [1,2,3]
print(tuple(lst))
Output
(1, 2, 3)
Tuple → List
t = (1,2,3)
print(list(t))
Output
[1, 2, 3]
Nested Tuple
t = ((1,2),(3,4))
print(t[1][0])
Output
3
2.
t = (1,2,2,3)
print([Link](2))
Output
2
3.
t = (5,10,15)
print([Link](10))
Output
1
4.
t = (10,20,30)
print(t[::-1])
Output
(30, 20, 10)
5.
a, b = (100,200)
print(a)
print(b)
Output
100
200
This is actually a common interview question: "When should I use a list and when should I use a tuple?"
The answer depends on whether the data changes.
3. Chat Messages
messages = []
New messages keep getting appended.
5. AI Dataset Images
images = ["[Link]", "[Link]"]
More images are added during preprocessing.
2. RGB Color
red = (255, 0, 0)
A color value is fixed.
3. Database Record ID
student = (101, "Bhargavi")
The ID should remain constant.
5. Image Resolution
resolution = (1920, 1080)
Width and height are fixed for that image.
AI/ML Examples
List
Training images:
dataset = []
[Link]("[Link]")
Images keep getting added.
Tuple
Image size:
input_shape = (224, 224, 3)
The model expects this fixed shape, so it shouldn't change.
Backend (Flask/FastAPI)
List
API response:
users = [
"Alice",
"Bob",
"Charlie"
]
Users are added and removed.
Tuple
HTTP status:
response = (
{"message": "Success"},
200
)
The response body and status code are returned together as a fixed pair.
Interview Rule
Use a List when data is expected to change.
Use a Tuple when data should remain constant.
Quick Comparison
Real-life Example List Tuple
Shopping Cart
WhatsApp Messages
Student Attendance
GPS Coordinates
RGB Color
Image Resolution
Days of the Week
Database ID + Name
Interview one-liner
Q: When would you choose a tuple over a list?
A: I use a tuple when the data is fixed and should not be modified, such as GPS coordinates, RGB colors, image dimensions, or
configuration values. I use a list when the data is dynamic and needs to be updated, such as shopping carts, chat messages, or
collections of users.
Sets
A set is an unordered, mutable collection of unique elements.
s = {10, 20, 30}
Properties
• Unordered
• Mutable
• No Duplicates
• No Indexing
• No Slicing
Creating Sets
s1 = {1, 2, 3}
s2 = {"Python", "Java"}
s4 = set()
Empty Set
s = {}
Output
<class 'dict'>
Correct:
s = set()
print(type(s))
Output
<class 'set'>
print(s)
Output
{10, 20, 30}
No Indexing
s = {10,20,30}
print(s[0])
Output
TypeError
Add Elements
add()
s = {10,20}
[Link](30)
print(s)
Output
{10, 20, 30}
update()
s = {1,2}
[Link]([3,4])
print(s)
Output
{1, 2, 3, 4}
Remove Elements
remove()
s = {10,20,30}
[Link](20)
print(s)
Output
{10, 30}
If the element doesn't exist:
[Link](50)
Output
KeyError
discard()
s = {10,20,30}
[Link](50)
print(s)
Output
{10, 20, 30}
No error.
pop()
s = {10,20,30}
print([Link]())
print(s)
Output (may vary)
10
{20, 30}
Since sets are unordered, pop() removes an arbitrary element.
clear()
s = {1,2,3}
[Link]()
print(s)
Output
set()
Membership
s = {10,20,30}
print(20 in s)
print(50 in s)
Output
True
False
Membership testing in a set is generally very fast.
Length
s = {10,20,30}
print(len(s))
Output
3
Set Operations
Union
a = {1,2,3}
b = {3,4,5}
print(a | b)
Output
{1, 2, 3, 4, 5}
or
print([Link](b))
Intersection
a = {1,2,3}
b = {2,3,4}
print(a & b)
Output
{2, 3}
or
print([Link](b))
Difference
a = {1,2,3}
b = {2,3,4}
print(a - b)
Output
{1}
Symmetric Difference
a = {1,2,3}
b = {2,3,4}
print(a ^ b)
Output
{1, 4}
Copy
a = {1,2,3}
b = [Link]()
print(b)
Output
{1, 2, 3}
Conversions
List → Set
lst = [1,2,2,3]
print(set(lst))
Output
{1, 2, 3}
Set → List
s = {1,2,3}
print(list(s))
Output
[1, 2, 3]
(Order may vary.)
print(s)
Output
{1, 2, 3}
s = {1,2}
[Link]([3,4])
print(s)
Output
{1, 2, 3, 4}
• add() → Adds one element.
• update() → Adds multiple elements from an iterable.
Real-Life Examples
1. Unique Usernames
usernames = {"alice", "bob", "charlie"}
No duplicate usernames.
2. Unique Tags
tags = {"python", "ai", "ml"}
Avoid duplicate tags.
unique_ids = set(ids)
Output
{101, 102, 103}
Practice Questions
1.
s = {10,20,30}
[Link](40)
print(s)
Output
{10, 20, 30, 40}
2.
s = {1,2,2,3}
print(s)
Output
{1, 2, 3}
3.
a = {1,2,3}
b = {3,4,5}
print(a | b)
Output
{1, 2, 3, 4, 5}
4.
a = {1,2,3}
b = {2,3,4}
print(a & b)
Output
{2, 3}
5.
a = {1,2,3}
b = {2,3,4}
print(a - b)
Output
{1}
Dictionary
A dictionary is an unordered (insertion order is preserved in Python 3.7+), mutable collection of key-value pairs.
student = {
"name": "Bhargavi",
"age": 21,
"cgpa": 9.35
}
Properties
• Key-Value pairs
• Mutable
• Keys must be unique
• Values can be duplicated
• Fast lookup using keys
Creating Dictionaries
student = {
"name": "Bhargavi",
"age": 21
}
empty = {}
d = dict()
Accessing Values
Using key
student = {
"name": "Bhargavi",
"age": 21
}
print(student["name"])
print(student["age"])
Output
Bhargavi
21
get()
print([Link]("name"))
Output
Bhargavi
If key doesn't exist
print([Link]("cgpa"))
Output
None
Default value
print([Link]("cgpa", 0))
Output
0
Adding Elements
student = {}
student["name"] = "Bhargavi"
student["age"] = 21
print(student)
Output
{'name': 'Bhargavi', 'age': 21}
Updating Elements
student["age"] = 22
print(student)
Output
{'name': 'Bhargavi', 'age': 22}
Removing Elements
pop()
student = {
"name":"Bhargavi",
"age":21
}
[Link]("age")
print(student)
Output
{'name': 'Bhargavi'}
del
del student["name"]
print(student)
Output
{}
clear()
student = {
"name":"Bhargavi",
"age":21
}
[Link]()
print(student)
Output
{}
Keys
student = {
"name":"Bhargavi",
"age":21
}
print([Link]())
Output
dict_keys(['name', 'age'])
Values
print([Link]())
Output
dict_values(['Bhargavi', 21])
Items
print([Link]())
Output
dict_items([('name', 'Bhargavi'), ('age', 21)])
Looping
Keys
for key in student:
print(key)
Output
name
age
Values
for value in [Link]():
print(value)
Output
Bhargavi
21
Membership
print("name" in student)
print("cgpa" in student)
Output
True
False
in checks keys, not values.
Length
print(len(student))
Output
2
Copy
new_student = [Link]()
print(new_student)
Output
{'name': 'Bhargavi', 'age': 21}
update()
student = {
"name":"Bhargavi"
}
[Link]({"age":21})
print(student)
Output
{'name': 'Bhargavi', 'age': 21}
Nested Dictionary
student = {
"name":"Bhargavi",
"marks":{
"math":95,
"science":98
}
}
print(student["marks"]["math"])
Output
95
Dictionary Comprehension
square = {x:x*x for x in range(1,6)}
print(square)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(d)
Output
{'a': 2}
Latest value overwrites the previous one.
print(d)
Output
{'a': 1, 'b': 1}
Yes.
Valid Keys
d={
1:"one",
"name":"Bhargavi",
(1,2):"tuple",
True:"yes"
}
Immutable types can be keys.
Real-Life Examples
Student Database
student = {
"USN":"4VV23CS001",
"Name":"Bhargavi",
"CGPA":9.35
}
API Response
response = {
"status":200,
"message":"Success",
"data":[]
}
Product
product = {
"id":101,
"name":"Laptop",
"price":65000
}
Frequency Counter
word = "banana"
freq = {}
for ch in word:
freq[ch] = [Link](ch,0)+1
print(freq)
Output
{'b': 1, 'a': 3, 'n': 2}
This is one of the most common interview patterns.
Practice Questions
1.
student = {
"name":"Bhargavi",
"age":21
}
print(student["name"])
Output
Bhargavi
2.
student = {}
student["cgpa"] = 9.35
print(student)
Output
{'cgpa': 9.35}
3.
student = {
"a":1,
"b":2
}
[Link]("a")
print(student)
Output
{'b': 2}
4.
student = {
"name":"Bhargavi",
"age":21
}
print([Link]())
Output
dict_keys(['name', 'age'])
5.
student = {
"name":"Bhargavi",
"age":21
}
for k, v in [Link]():
print(k, v)
Output
name Bhargavi
age 21
Interview Tip
If you remember only one use case for dictionaries, remember this:
Frequency Counting
freq = {}
for x in arr:
freq[x] = [Link](x, 0) + 1
This pattern appears in countless coding interview problems:
• Character frequency
• Word frequency
• Top K Frequent Elements
• Group Anagrams
• Two Sum
• First Unique Character
• Count occurrences
Master dictionaries—they are one of the most important data structures in Python for both interviews and real-world
programming.
Control Flow
Control flow decides the order in which statements are executed.
There are three types:
1. Decision Making (if, elif, else, match-case)
2. Loops (for, while)
3. Loop Control (break, continue, pass)
1. if Statement
Syntax
if condition:
statements
Example
age = 20
2. if-else
age = 15
3. if-elif-else
marks = 85
4. Nested if
age = 20
citizen = True
5. Short-hand if
a = 10
if a > 5: print("Greater")
Output
Greater
6. Ternary Operator
Syntax
value_if_true if condition else value_if_false
Example
age = 20
print(msg)
Output
Adult
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case _:
print("Invalid")
Output
Tuesday
_ acts like default.
8. for Loop
for i in range(5):
print(i)
Output
0
1
2
3
4
range()
One argument
for i in range(5):
print(i)
Output
01234
Two arguments
for i in range(2,6):
print(i)
Output
2345
Three arguments
for i in range(2,10,2):
print(i)
Output
2468
Loop through String
for ch in "Python":
print(ch)
Output
P
y
t
h
o
n
for i in nums:
print(i)
Output
10
20
30
while Loop
i=1
while i <= 5:
print(i)
i += 1
Output
1
2
3
4
5
Infinite Loop
while True:
print("Hello")
Runs forever until interrupted.
break
Stops the loop.
for i in range(10):
if i == 5:
break
print(i)
Output
0
1
2
3
4
continue
Skips the current iteration.
for i in range(5):
if i == 2:
continue
print(i)
Output
0
1
3
4
pass
Placeholder. Does nothing.
for i in range(5):
if i == 2:
pass
print(i)
Output
0
1
2
3
4
Another example:
if True:
pass
Useful when writing incomplete code.
enumerate()
Returns (index, value).
fruits = ["Apple","Banana","Mango"]
zip()
Combines multiple iterables.
names = ["Alice","Bob"]
marks = [90,95]
Loop else
for i in range(3):
print(i)
else:
print("Done")
Output
0
1
2
Done
If break executes, the else block is skipped.
range(5)
01234
range(1,5)
1234
range(1,10,2)
13579
Practice Questions
1.
for i in range(1,6):
print(i)
2.
i=5
while i >= 1:
print(i)
i -= 1
3.
for i in range(5):
if i == 3:
break
print(i)
4.
for i in range(5):
if i == 2:
continue
print(i)
5.
fruits = ["Apple","Banana","Mango"]
6.
a = [1,2,3]
b = ["A","B","C"]
Functions
A function is a reusable block of code that performs a specific task.
Instead of writing the same code multiple times, write it once and call it whenever needed.
Syntax
def function_name(parameters):
# code
return value
1. Simple Function
def greet():
print("Hello")
greet()
Output
Hello
greet("Bhargavi")
Output
Hello Bhargavi
print(result)
Output
30
return vs print
def add(a, b):
print(a + b)
x = add(2,3)
print(x)
Output
5
None
Because print() displays the value but doesn't return it.
Correct:
def add(a,b):
return a+b
x = add(2,3)
print(x)
Output
5
Default Arguments
def greet(name="Guest"):
print(f"Hello {name}")
greet()
greet("Bhargavi")
Output
Hello Guest
Hello Bhargavi
Keyword Arguments
def student(name, age):
print(name, age)
student(age=21, name="Bhargavi")
Output
Bhargavi 21
Order doesn't matter.
Positional Arguments
def student(name, age):
print(name, age)
student("Bhargavi", 21)
Output
Bhargavi 21
Order matters.
*args
Accepts multiple positional arguments.
def add(*nums):
print(nums)
add(10,20,30)
Output
(10, 20, 30)
Another example
def add(*nums):
print(sum(nums))
add(10,20,30)
Output
60
**kwargs
Accepts multiple keyword arguments.
def student(**details):
print(details)
student(name="Bhargavi", age=21)
Output
{'name': 'Bhargavi', 'age': 21}
Scope
Local Variable
def fun():
x = 10
print(x)
fun()
Output
10
Global Variable
x = 100
def fun():
print(x)
fun()
Output
100
global Keyword
x = 10
def fun():
global x
x = 50
fun()
print(x)
Output
50
Lambda Function
Anonymous function.
Syntax
lambda arguments : expression
Example
square = lambda x: x*x
print(square(5))
Output
25
Multiple arguments
add = lambda a,b: a+b
print(add(10,20))
Output
30
map()
Applies a function to every element.
nums = [1,2,3]
print(result)
Output
[2, 4, 6]
filter()
Filters elements.
nums = [1,2,3,4,5]
print(result)
Output
[2, 4]
reduce()
Need to import it.
from functools import reduce
nums = [1,2,3,4]
print(result)
Output
10
Recursion
Function calling itself.
def factorial(n):
if n==1:
return 1
return n*factorial(n-1)
print(factorial(5))
Output
120
Docstring
def add(a,b):
"""Returns sum"""
return a+b
print(add.__doc__)
Output
Returns sum
fun(1,2,3,4)
Output
(1, 2, 3, 4)
def fun(**kwargs):
print(kwargs)
fun(name="Bhargavi", age=21)
Output
{'name': 'Bhargavi', 'age': 21}
Interview Questions
Difference between parameter and argument
def add(a,b):
return a+b
add(10,20)
• Parameters → a, b
• Arguments → 10, 20
Practice Questions
1.
def square(n):
return n*n
print(square(6))
Output
36
2.
def greet(name="Guest"):
print(name)
greet()
Output
Guest
3.
add = lambda a,b:a+b
print(add(10,20))
Output
30
4.
nums=[1,2,3]
print(list(map(lambda x:x+1,nums)))
Output
[2, 3, 4]
5.
nums=[1,2,3,4]
print(list(filter(lambda x:x%2==0,nums)))
Output
[2, 4]
6.
from functools import reduce
print(reduce(lambda a,b:a+b,[1,2,3]))
Output
6
1. Class
A class is a blueprint/template for creating objects.
Example:
• Class → Car
• Objects → BMW, Audi, Tesla
Syntax
class Student:
pass
2. Object
An object is an instance of a class.
class Student:
pass
s1 = Student()
print(type(s1))
Output
<class '__main__.Student'>
3. Constructor (__init__)
A constructor is automatically called when an object is created.
class Student:
def __init__(self):
print("Constructor called")
s1 = Student()
Output
Constructor called
s1 = Student("Bhargavi", 21)
print([Link])
print([Link])
Output
Bhargavi
21
4. self
This is one of the most common interview questions.
self refers to the current object.
class Student:
s1 = Student("Bhargavi")
s2 = Student("Rahul")
print([Link])
print([Link])
Output
Bhargavi
Rahul
Without self, each object wouldn't have its own data.
5. Instance Method
class Student:
def display(self):
print([Link])
s = Student("Bhargavi")
[Link]()
Output
Bhargavi
6. Instance Variables
class Student:
s1 = Student("Bhargavi")
s2 = Student("Rahul")
print([Link])
print([Link])
Each object has its own copy of name.
Interview Questions
What is a class?
A blueprint for creating objects.
What is an object?
An instance of a class.
What is a constructor?
A special method (__init__) that runs automatically when an object is created.
Why do we use self?
self refers to the current object and allows each object to access its own attributes and methods.
Practice
1.
class Car:
c = Car("BMW")
print([Link])
Output
BMW
2.
class Student:
s = Student("Bhargavi", 9.35)
print([Link])
print([Link])
Output
Bhargavi
9.35
This is Part 1 of OOP. Learn these concepts first because everything else (inheritance, polymorphism, super(), static methods,
etc.) builds on them.
After this, we'll move to Inheritance, which is the next major OOP concept.
What is Inheritance?
Inheritance allows one class (Child/Subclass) to acquire the properties and methods of another class (Parent/Superclass).
Real-life Example
Think of a family:
Parent
│
▼
Child
A child inherits characteristics from the parent.
Similarly in programming,
Animal
│
▼
Dog
The Dog class can use everything from the Animal class.
class Cat:
def eat(self):
print("Eating")
The same code is repeated.
With inheritance:
class Animal:
def eat(self):
print("Eating")
class Dog(Animal):
pass
class Cat(Animal):
pass
Now both Dog and Cat automatically have the eat() method.
This follows the DRY Principle (Don't Repeat Yourself).
Syntax
class Parent:
...
class Child(Parent):
...
Example 1
class Animal:
def eat(self):
print("Animal is eating")
class Dog(Animal):
pass
dog = Dog()
[Link]()
Output
Animal is eating
The Dog class doesn't have an eat() method, but it inherits it from Animal.
Example 2
class Animal:
def eat(self):
print("Eating")
class Dog(Animal):
def bark(self):
print("Barking")
dog = Dog()
[Link]()
[Link]()
Output
Eating
Barking
The child class can:
• Use parent methods
• Have its own methods
Constructor Inheritance
class Animal:
def __init__(self):
print("Animal Constructor")
class Dog(Animal):
pass
dog = Dog()
Output
Animal Constructor
The parent's constructor is inherited if the child doesn't define its own.
def __init__(self):
print("Animal Constructor")
class Dog(Animal):
def __init__(self):
print("Dog Constructor")
dog = Dog()
Output
Dog Constructor
The parent's constructor is not called automatically because the child overrides it.
We'll see how to call it using super() later.
isinstance()
Checks if an object belongs to a class.
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
Output
True
True
A Dog object is also an Animal.
issubclass()
Checks inheritance between classes.
class Animal:
pass
class Dog(Animal):
pass
print(issubclass(Dog, Animal))
Output
True
Types of Inheritance
Python supports 5 types:
1. Single
2. Multiple
3. Multilevel
4. Hierarchical
5. Hybrid
We'll study each one separately.
1. Single Inheritance
One parent → One child
Animal
│
▼
Dog
class Animal:
def eat(self):
print("Eating")
class Dog(Animal):
def bark(self):
print("Barking")
dog = Dog()
[Link]()
[Link]()
Output
Eating
Barking
2. Multilevel Inheritance
Grandparent → Parent → Child
Animal
│
Mammal
│
Dog
class Animal:
def eat(self):
print("Eating")
class Mammal(Animal):
def walk(self):
print("Walking")
class Dog(Mammal):
def bark(self):
print("Barking")
dog = Dog()
[Link]()
[Link]()
[Link]()
Output
Eating
Walking
Barking
3. Hierarchical Inheritance
One parent → Multiple children
Animal
/ \
Dog Cat
class Animal:
def eat(self):
print("Eating")
class Dog(Animal):
def bark(self):
print("Bark")
class Cat(Animal):
def meow(self):
print("Meow")
dog = Dog()
cat = Cat()
[Link]()
[Link]()
Output
Eating
Eating
4. Multiple Inheritance
Multiple parents → One child
Father Mother
\ /
Child
class Father:
def skill1(self):
print("Driving")
class Mother:
def skill2(self):
print("Cooking")
c = Child()
c.skill1()
c.skill2()
Output
Driving
Cooking
5. Hybrid Inheritance
Combination of two or more inheritance types.
Python supports it.
We'll understand it better when we study MRO.
Advantages
Code Reusability
Less Code Duplication
Easier Maintenance
Better Organization
Interview Questions
What is inheritance?
Acquiring properties and methods of another class.
class Dog(Animal):
def bark(self):
print("Bark")
animal = Animal()
[Link]()
Output
AttributeError
Practice Questions
1.
class Vehicle:
def start(self):
print("Vehicle Started")
class Car(Vehicle):
pass
c = Car()
[Link]()
2.
class A:
def show(self):
print("A")
class B(A):
def display(self):
print("B")
b = B()
[Link]()
[Link]()
3.
class A:
def fun(self):
print("A")
class B:
def demo(self):
print("B")
c = C()
[Link]()
[Link]()
Next Topic
The next topic is Method Overriding + super(), which naturally builds on inheritance and is one of the most frequently asked
Python OOP interview topics.
Perfect! Now we'll cover Method Overriding and super(), which are among the most frequently asked OOP interview topics.
Example 1
class Animal:
def sound(self):
print("Animal makes sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
dog = Dog()
[Link]()
Output
Dog barks
The child's sound() method overrides the parent's sound() method.
def sound(self):
print("Animal makes sound")
class Dog(Animal):
pass
dog = Dog()
[Link]()
Output
Animal makes sound
Python uses the parent's method.
Why Override?
Different child classes can provide their own behavior.
Example:
class Animal:
def sound(self):
print("Animal Sound")
class Dog(Animal):
def sound(self):
print("Bark")
class Cat(Animal):
def sound(self):
print("Meow")
Dog().sound()
Cat().sound()
Output
Bark
Meow
super()
super() is used to access the parent class.
It is commonly used to:
• Call the parent constructor
• Call parent methods
def sound(self):
print("Animal Sound")
class Dog(Animal):
def sound(self):
super().sound()
print("Dog Bark")
Dog().sound()
Output
Animal Sound
Dog Bark
Execution:
1. super().sound() → Parent method
2. Child method continues
Without super()
class Animal:
def sound(self):
print("Animal")
class Dog(Animal):
def sound(self):
print("Dog")
Dog().sound()
Output
Dog
Parent method is completely ignored.
Parent Constructor
Without super()
class Animal:
def __init__(self):
print("Animal Constructor")
class Dog(Animal):
def __init__(self):
print("Dog Constructor")
Dog()
Output
Dog Constructor
Parent constructor isn't called.
Using super()
class Animal:
def __init__(self):
print("Animal Constructor")
class Dog(Animal):
def __init__(self):
super().__init__()
print("Dog Constructor")
Dog()
Output
Animal Constructor
Dog Constructor
class Dog(Animal):
print([Link])
print([Link])
Output
Bruno
Labrador
def show(self):
print("A")
class B(A):
def show(self):
super().show()
print("B")
B().show()
Output
A
B
We'll study MRO in detail later.
Interview Questions
What is Method Overriding?
Redefining a parent's method in the child class with the same name and parameters.
Practice Questions
1.
class Person:
def greet(self):
print("Hello")
class Student(Person):
def greet(self):
print("Hi")
Student().greet()
Output
Hi
2.
class A:
def show(self):
print("A")
class B(A):
def show(self):
super().show()
print("B")
B().show()
Output
A
B
3.
class Animal:
def __init__(self):
print("Animal")
class Dog(Animal):
def __init__(self):
super().__init__()
print("Dog")
Dog()
Output
Animal
Dog
Next Topic
We'll cover Polymorphism, where you'll learn:
• Compile-time vs Runtime Polymorphism
• Duck Typing
• Operator Overloading
• Method Overloading (Python approach)
• Practical interview examples
This is another high-frequency OOP interview topic.
Perfect! Now we'll study Polymorphism, one of the four pillars of OOP.
Types of Polymorphism
There are two types:
1. Compile-Time Polymorphism (Method Overloading)
2. Run-Time Polymorphism (Method Overriding)
1. Runtime Polymorphism
Achieved using Method Overriding.
class Animal:
def sound(self):
print("Animal Sound")
class Dog(Animal):
def sound(self):
print("Bark")
class Cat(Animal):
def sound(self):
print("Meow")
Dog().sound()
Cat().sound()
Output
Bark
Meow
Same method → Different behavior.
2. Compile-Time Polymorphism
Languages like Java support:
add(int a, int b)
def show(self):
print("First")
def show(self):
print("Second")
t = Test()
[Link]()
Output
Second
The second method replaces the first.
print(add(10))
print(add(10, 20))
print(add(10, 20, 30))
Output
10
30
60
Or using *args.
def add(*nums):
return sum(nums)
print(add(10))
print(add(10,20))
print(add(10,20,30))
Output
10
30
60
Operator Overloading
Operators work differently for different data types.
print(10 + 20)
Output
30
print([1,2] + [3,4])
Output
[1, 2, 3, 4]
Same operator (+) → Different behavior.
This is operator overloading.
Another Example
print(5 * 3)
Output
15
print("Hi" * 3)
Output
HiHiHi
Again, same operator, different behavior.
Duck Typing
One of Python's unique features.
Principle
If it walks like a duck and quacks like a duck, it's a duck.
Python doesn't care about the object's type.
It only cares whether the required method exists.
Example
class Dog:
def speak(self):
print("Bark")
class Cat:
def speak(self):
print("Meow")
def animal_sound(animal):
[Link]()
animal_sound(Dog())
animal_sound(Cat())
Output
Bark
Meow
Notice:
The function never checks
if isinstance(...)
It simply calls
[Link]()
If the object has speak(), it works.
Built-in Polymorphism
The same built-in function behaves differently.
len()
print(len("Python"))
Output
6
print(len([1,2,3]))
Output
3
print(len((1,2)))
Output
2
Same function → Different objects.
abs()
print(abs(-10))
Output
10
print(abs(-5.7))
Output
5.7
isinstance()
print(isinstance(5,int))
Output
True
Works with many object types.
Advantages
• Code Reusability
• Flexibility
• Easy Extension
• Loose Coupling
• Cleaner Design
Interview Questions
What is polymorphism?
One interface, many implementations.
Types of polymorphism?
• Compile-Time
• Run-Time
Practice Questions
1.
class Bird:
def sound(self):
print("Bird")
class Sparrow(Bird):
def sound(self):
print("Chirp")
Sparrow().sound()
Output
Chirp
2.
def add(a, b=0):
return a+b
print(add(10))
print(add(10,20))
Output
10
30
3.
print("AI" * 3)
Output
AIAIAI
4.
class Student:
def show(self):
print("Student")
class Teacher:
def show(self):
print("Teacher")
def display(obj):
[Link]()
display(Student())
display(Teacher())
Output
Student
Teacher
Placement Takeaway
If an interviewer asks "Explain polymorphism in Python", mention these four points:
1. Method Overriding (Runtime Polymorphism)
2. Method Overloading using default arguments or *args
3. Operator Overloading (+, *, etc.)
4. Duck Typing (Python-specific and commonly asked)
These cover almost every polymorphism-related interview question for Python.
What is Encapsulation?
Encapsulation means wrapping data (variables) and methods (functions) into a single unit (class) and restricting direct access
to some of the object's data.
In simple words:
Hide the internal data and allow controlled access through methods.
Real-Life Example
Think of an ATM.
You can:
• Withdraw money
• Deposit money
• Check balance
But you cannot directly change your bank balance inside the bank's database.
Customer
│
▼
ATM
│
▼
Bank Database
The ATM provides controlled access.
Why Encapsulation?
• Protect data
• Prevent accidental modification
• Improve security
• Make code easier to maintain
1. Public Members
Accessible from anywhere.
class Student:
def __init__(self):
[Link] = "Bhargavi"
s = Student()
print([Link])
Output
Bhargavi
2. Protected Members
Starts with one underscore.
class Student:
def __init__(self):
self._name = "Bhargavi"
s = Student()
print(s._name)
Output
Bhargavi
Important:
Python does not actually prevent access.
_name is only a convention that means:
"Please don't access this from outside."
3. Private Members
Starts with two underscores.
class Student:
def __init__(self):
self.__name = "Bhargavi"
s = Student()
print(s.__name)
Output
AttributeError
Python uses name mangling to make direct access difficult.
def __init__(self):
self.__name = "Bhargavi"
def display(self):
print(self.__name)
s = Student()
[Link]()
Output
Bhargavi
Private variables are meant to be accessed through class methods.
Name Mangling
Python internally changes
__name
to
_ClassName__name
Example
class Student:
def __init__(self):
self.__name = "Bhargavi"
s = Student()
print(s._Student__name)
Output
Bhargavi
This works, but it's mainly for special cases. You generally shouldn't rely on it.
def __init__(self):
self.__age = 21
def get_age(self):
return self.__age
s = Student()
print(s.get_age())
s.set_age(22)
print(s.get_age())
Output
21
22
def __init__(self):
self.__age = 21
if age > 0:
self.__age = age
else:
print("Invalid Age")
def get_age(self):
return self.__age
s = Student()
s.set_age(-5)
print(s.get_age())
Output
Invalid Age
21
Without encapsulation, someone could accidentally write:
[Link] = -100
Using @property
Python provides a cleaner way.
class Student:
def __init__(self):
self.__age = 21
@property
def age(self):
return self.__age
@[Link]
def age(self, value):
if value > 0:
self.__age = value
s = Student()
print([Link])
[Link] = 22
print([Link])
Output
21
22
Now you can access it like a variable while still controlling changes.
Interview Questions
What is encapsulation?
Binding data and methods into one class while restricting direct access to data.
What is @property?
It lets you use methods as if they were attributes, making code cleaner while still allowing validation.
Practice Questions
1.
class Employee:
def __init__(self):
self.__salary = 50000
def get_salary(self):
return self.__salary
e = Employee()
print(e.get_salary())
Output
50000
2.
class Student:
def __init__(self):
self._name = "Bhargavi"
s = Student()
print(s._name)
Output
Bhargavi
3.
class Test:
def __init__(self):
self.__x = 10
t = Test()
print(t.__x)
Output
AttributeError
Real-Life Examples
• Bank Account → Balance is private; transactions go through methods.
• ATM → Users interact with buttons, not the bank database directly.
• Instagram → You can't directly edit follower counts in the database.
• E-commerce → Product price updates go through validation, not direct modification.
Placement Summary
Remember these points:
• Public → Accessible everywhere.
• Protected (_) → Convention for internal use.
• Private (__) → Uses name mangling to discourage direct access.
• Use getters/setters or @property for controlled access and validation.
Next Topic
We'll cover Abstraction, the final pillar of OOP. After that, we'll finish with:
• @staticmethod
• @classmethod
• Multiple Inheritance
• MRO (Method Resolution Order)
These complete the Python OOP syllabus for placements.
What is Abstraction?
Abstraction means hiding implementation details and showing only the essential features.
The user knows WHAT to do, not HOW it is done.
Real-Life Example
Think about driving a car.
You only know:
• Steering
• Accelerator
• Brake
• Gear
You don't need to know how the engine, transmission, fuel injection, etc. work internally.
You
│
▼
Steering Brake Accelerator
│
▼
Hidden Engine Mechanism
The internal implementation is hidden.
More Examples
ATM
You press:
• Withdraw
• Deposit
• Check Balance
You don't know the banking algorithms running behind the scenes.
Mobile Phone
You press
Call Mom
You don't know
• Signal transmission
• Towers
• Network routing
Why Abstraction?
• Hide complexity
• Increase security
• Easier to use
• Easier maintenance
Abstraction in Python
Python provides abstraction using the abc (Abstract Base Class) module.
from abc import ABC, abstractmethod
Abstract Class
An abstract class cannot be instantiated.
from abc import ABC
class Animal(ABC):
pass
a = Animal()
Output
TypeError
Abstract Method
An abstract method has no implementation in the parent.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
Notice
pass
No implementation.
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Bark")
dog = Dog()
[Link]()
Output
Bark
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
pass
Dog()
Output
TypeError:
Can't instantiate abstract class Dog
with abstract method sound
Because every abstract method must be implemented.
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def area(self):
return 20
def perimeter(self):
return 18
r = Rectangle()
print([Link]())
print([Link]())
Output
20
18
Real-Life Example
Suppose you're developing a payment system.
Every payment must implement
• pay()
But payment methods differ.
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def pay(self):
pass
class UPI(Payment):
def pay(self):
print("Pay using UPI")
class CreditCard(Payment):
def pay(self):
print("Pay using Card")
UPI().pay()
CreditCard().pay()
Output
Pay using UPI
Pay using Card
The parent class forces every payment method to provide its own implementation.
class Animal(ABC):
def eat(self):
print("Eating")
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Bark")
dog = Dog()
[Link]()
[Link]()
Output
Eating
Bark
Only sound() is abstract.
Interview Questions
What is abstraction?
Hiding implementation details while exposing only the essential functionality.
class A(ABC):
def __init__(self):
print("Constructor")
Practice Questions
1.
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
class Car(Vehicle):
def start(self):
print("Car Started")
Car().start()
Output
Car Started
2.
from abc import ABC, abstractmethod
class Test(ABC):
@abstractmethod
def show(self):
pass
class Demo(Test):
pass
Demo()
Output
TypeError
3.
from abc import ABC, abstractmethod
class Animal(ABC):
def eat(self):
print("Eating")
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Bark")
Dog().eat()
Output
Eating
Real-Life Examples
Example Hidden Part
ATM Banking logic
Car Engine mechanism
Mobile Phone Communication protocols
TV Remote Signal transmission
Payment Gateway Payment processing
Placement Summary
Remember these key points:
• Abstraction hides implementation details.
• Use the abc module and @abstractmethod.
• Abstract classes cannot be instantiated.
• Child classes must implement all abstract methods.
• Abstract classes can still have:
o Constructors
o Normal methods
o Instance variables
Next Topic
Next we'll cover @staticmethod and @classmethod, another favorite Python interview topic. These are asked very frequently
because they test whether you understand the difference between instance methods, class methods, and static methods.
Perfect! This is one of the most frequently asked Python interview topics.
OOP Part 7 – Instance Methods vs Class Methods vs Static Methods
This topic confuses many people, but after this you'll never forget it.
s1 = Student()
s2 = Student()
There are two kinds of variables:
Instance Variables
Each object has its own copy.
class Student:
[Link] = "Rahul"
Different values.
Class Variables
Shared by every object.
class Student:
college = "VVCE"
[Link]
Every student belongs to the same college.
Example
class Student:
college = "VVCE"
s1 = Student("Bhargavi")
s2 = Student("Rahul")
print([Link])
print([Link])
print([Link])
print([Link])
Output
Bhargavi
Rahul
VVCE
VVCE
Instance Method
Works with instance variables.
Uses
self
Example
class Student:
def display(self):
print([Link])
s = Student("Bhargavi")
[Link]()
Output
Bhargavi
Class Method
Works with class variables.
Uses
cls
Decorator
@classmethod
Example
class Student:
college = "VVCE"
@classmethod
def show_college(cls):
print([Link])
Student.show_college()
Output
VVCE
Another Example
class Student:
college = "VVCE"
@classmethod
def change_college(cls, name):
[Link] = name
Student.change_college("MIT")
print([Link])
Output
MIT
Notice:
All students now belong to MIT.
Static Method
Doesn't use
• self
• cls
Decorator
@staticmethod
Used for utility/helper functions.
Example
class Math:
@staticmethod
def add(a, b):
return a+b
print([Link](10,20))
Output
30
No object needed.
Another Example
class Student:
@staticmethod
def welcome():
print("Welcome Students")
[Link]()
Output
Welcome Students
Real-Life Example
Suppose
class Student
Instance Variable
name
age
cgpa
These are different for every student.
Use
self
Class Variable
college
principal
university
Same for every student.
Use
cls
Static Method
percentage_to_grade()
cgpa_to_percentage()
validate_email()
Independent utility functions.
Use
@staticmethod
Complete Example
class Student:
college = "VVCE"
def display(self):
print([Link])
@classmethod
def show_college(cls):
print([Link])
@staticmethod
def greet():
print("Welcome")
s = Student("Bhargavi")
[Link]()
Student.show_college()
[Link]()
Output
Bhargavi
VVCE
Welcome
deposit()
calculate_salary()
display_student()
Class Method
Needs class data.
Example
change_college()
change_company_name()
change_tax_rate()
Static Method
Needs neither object nor class.
Example
calculate_area()
convert_temperature()
validate_email()
Factory Method
One common use of @classmethod is creating objects in different ways.
class Student:
@classmethod
def from_string(cls, data):
return cls(data)
s = Student.from_string("Bhargavi")
print([Link])
Output
Bhargavi
This pattern is used in many libraries.
Interview Questions
Difference between self and cls
self cls
Current object Current class
Instance method Class method
college = "VVCE"
def show(self):
print([Link])
Student().show()
Output
VVCE
@staticmethod
def fun():
print("Hello")
def show(self):
[Link]()
A().show()
Output
Hello
@staticmethod
def fun():
print("Hello")
@classmethod
def show(cls):
[Link]()
[Link]()
Output
Hello
Practice Questions
1.
class Test:
@staticmethod
def hello():
print("Hello")
[Link]()
Output
Hello
2.
class Student:
college = "VVCE"
@classmethod
def show(cls):
print([Link])
[Link]()
Output
VVCE
3.
class Student:
def display(self):
print([Link])
Student("Bhargavi").display()
Output
Bhargavi
Comparison Table
Feature Instance Method Class Method Static Method
Decorator None @classmethod @staticmethod
First Parameter self cls None
Access Instance Variables Yes No No
Access Class Variables Yes Yes No (unless using class name)
Called Using Object Class/Object Class/Object
Purpose Object-specific operations Class-wide operations Utility/helper functions
Next Topic
The next and final OOP topic is Method Resolution Order (MRO) and Multiple Inheritance, which explains how Python decides
which method to execute when multiple parent classes define the same method. This is a very common Python interview
question.