0% found this document useful (0 votes)
3 views98 pages

Python Interview

This document provides an overview of Python, a high-level, interpreted, object-oriented programming language created by Guido van Rossum in 1991. It covers key features, common uses, advantages, and disadvantages of Python, as well as important interview questions and input/output operations. The document emphasizes practical knowledge for interviews and coding, focusing on essential concepts like dynamic typing, variable declaration, and the use of built-in functions.

Uploaded by

heyy8985
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views98 pages

Python Interview

This document provides an overview of Python, a high-level, interpreted, object-oriented programming language created by Guido van Rossum in 1991. It covers key features, common uses, advantages, and disadvantages of Python, as well as important interview questions and input/output operations. The document emphasizes practical knowledge for interviews and coding, focusing on essential concepts like dynamic typing, variable declaration, and the use of built-in functions.

Uploaded by

heyy8985
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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).

6. Huge Standard Library


Python comes with many built-in modules.
Examples:
math
os
random
datetime
collections
heapq
itertools

7. Open Source
Python is free to use and has a large community.

8. Extensive Third-Party Libraries


Examples:
• NumPy
• Pandas
• TensorFlow
• PyTorch
• Flask
• FastAPI
• OpenCV

Where Python is Used


• AI/ML
• Data Science
• Backend Development
• Automation
• Web Scraping
• APIs
• DevOps
• Cloud
• IoT

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]

Why is Python Popular in AI/ML?


Because of libraries like:
• NumPy
• Pandas
• scikit-learn
• TensorFlow
• PyTorch
They simplify complex mathematical and machine learning tasks.

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

2. When was Python released?


1991

3. Is Python compiled or interpreted?


Python is generally considered an interpreted language. In CPython, source code is first compiled to bytecode, which is then
executed by the Python Virtual Machine (PVM).

4. Why is Python called dynamically typed?


Because the type is associated with the value, not the variable.
x = 10
x = "Python"

5. Why is Python platform independent?


Because the same Python source code can run on different operating systems with a compatible Python interpreter.

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

Practice (10 minutes)


1. What is Python?
2. Why is Python called dynamically typed?
3. Difference between compiled and interpreted languages?
4. Who created Python?
5. Name five features of Python.
6. What is PEP 8?
7. Why is Python popular for AI/ML?

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).

6. Huge Standard Library


Python comes with many built-in modules.
Examples:
math
os
random
datetime
collections
heapq
itertools

7. Open Source
Python is free to use and has a large community.

8. Extensive Third-Party Libraries


Examples:
• NumPy
• Pandas
• TensorFlow
• PyTorch
• Flask
• FastAPI
• OpenCV

Where Python is Used


• AI/ML
• Data Science
• Backend Development
• Automation
• Web Scraping
• APIs
• DevOps
• Cloud
• IoT

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]

Why is Python Popular in AI/ML?


Because of libraries like:
• NumPy
• Pandas
• scikit-learn
• TensorFlow
• PyTorch
They simplify complex mathematical and machine learning tasks.

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

2. When was Python released?


1991

3. Is Python compiled or interpreted?


Python is generally considered an interpreted language. In CPython, source code is first compiled to bytecode, which is then
executed by the Python Virtual Machine (PVM).

4. Why is Python called dynamically typed?


Because the type is associated with the value, not the variable.
x = 10
x = "Python"

5. Why is Python platform independent?


Because the same Python source code can run on different operating systems with a compatible Python interpreter.

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

Practice (10 minutes)


1. What is Python?
2. Why is Python called dynamically typed?
3. Difference between compiled and interpreted languages?
4. Who created Python?
5. Name five features of Python.
6. What is PEP 8?
7. Why is Python popular for AI/ML?

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.

Great! Let's learn Input & Output.

Input and Output in Python


Every program mainly does three things:
Input → Process → Output
Example:
Input: 5, 10

Addition

Output: 15

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.

Printing Multiple Values


name = "Bhargavi"
age = 21

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

Very Important Interview Question


What does input() return?
Answer:
input() always returns a string, even if the user enters a number.
Example:
age = input("Enter age: ")

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

Taking Different Types of Input


Integer
age = int(input("Enter age: "))

Float
salary = float(input("Enter salary: "))
String
name = input("Enter name: ")

Boolean
There's no direct boolean input.
flag = input("Enter True or False: ")

flag = [Link]() == "true"

print(flag)

Taking Multiple Inputs


Method 1:
a, b = input("Enter two numbers: ").split()

print(a)
print(b)
Input:
10 20

Method 2 (Most Common)


a, b = map(int, input("Enter two numbers: ").split())

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

Formatting Output (Preview)


name = "Bhargavi"
cgpa = 9.35

print(f"Name: {name}, CGPA: {cgpa}")


Output:
Name: Bhargavi, CGPA: 9.35
We'll cover f-strings in detail later.

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.

1. Print your name, age, and college


Your answer:
print("bhargavi,20,vvce")
This prints exactly one string, which is acceptable.
A more Pythonic way is:
print("Bhargavi", 20, "VVCE")
Output:
Bhargavi 20 VVCE
Or if you want commas:
print("Bhargavi", 20, "VVCE", sep=",")
Output:
Bhargavi,20,VVCE

2. Take name as input


Your answer:
name=input("enter name")
print(f"Hello,{name})
Missing the closing quotation mark.
Correct:
name = input("Enter name: ")
print(f"Hello, {name}")

3. Sum of two numbers


Your answer:
a,b=map(int,input("enter a and b").split())
print(a+b)
Perfect.

4. Average of three numbers


Your answer:
a,b,c=map(float,input("enter a b c").split())
print((a+b+c)/3)
Perfect.

5. Print
Python -> Java -> C++
Use the sep parameter.
Try:
print("Python", "Java", "C++", sep=" -> ")
Output:
Python -> Java -> C++

6. Print Hello and World on the same line


Normally:
print("Hello")
print("World")
Output:
Hello
World
Using end:
print("Hello", end=" ")
print("World")
Output:
Hello World
You could also use:
print("Hello", end="---")
print("World")
Output:
Hello---World

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

student-name = "" # Hyphen not allowed

class = 10 # Keyword

Naming Convention (PEP 8)


Use snake_case.
student_name = "Bhargavi"
total_marks = 500
Avoid:
StudentName
studentName

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}

Truthy and Falsy


Python treats some values as False in boolean contexts.
Falsy values:
False
0
0.0
''
[]
()
{}
set()
None
Everything else is generally considered truthy.
Example:
if "":
print("Hello")
else:
print("Empty")
Output:
Empty

Common Interview Questions


1. Is Python statically or dynamically typed?
Answer: Dynamically typed.

2. Difference between type() and isinstance()?


• type() returns the exact type of an object.
• isinstance() checks whether an object is an instance of a specified type (including subclasses).

3. What does id() do?


Returns the identity (unique identifier) of an object during its lifetime.

4. What is None?
A special object representing the absence of a value.

5. Can a variable change its data type?


Yes.
x = 10
x = "Python"
x = 3.14

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)

Revision Cheat Sheet


• type(obj) → Returns the object's type.
• id(obj) → Returns the object's identity.
• isinstance(obj, type) → Checks the object's type.
• Python is dynamically typed.
• Use snake_case for variable names.
• None means "no value."
• Type conversion:
o int()
o float()
o str()
o bool()
o list()
o tuple()
o set()

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.

Sure! I'll only give the answers and outputs.

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'>

2. Swap two numbers without using a third variable.


a = 10
b = 20

a, b = b, a

print(a, b)
Output
20 10

3. Convert "250" to an integer and multiply it by 2.


num = "250"

num = int(num)

print(num * 2)
Output
500

4. Convert 150 to a string and print its type.


num = 150

num = str(num)

print(type(num))
Output
<class 'str'>

5. Check whether 9.35 is a float using isinstance().


print(isinstance(9.35, float))
Output
True

6. Predict the output.


a = 10
b = 10.0

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

2. Comparison (Relational) Operators


Returns True or False.
Operator Meaning
== Equal
!= Not Equal
> Greater Than
< Less Than
>= Greater Than or Equal
<= Less Than or Equal
Example:
a = 10
b = 20

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 < b and b > 15)


print(a > b or b > 15)
print(not(a < b))
Output
True
True
False
5. Identity Operators
Checks whether two variables refer to the same object.
Operator Meaning
is Same object
is not Different objects
Example:
a = [1, 2]
b=a
c = [1, 2]

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.)

Operator Precedence (High → Low)


1. () (Parentheses)
2. **
3. *, /, //, %
4. +, -
5. Comparison (==, <, >, etc.)
6. not
7. and
8. or
Example:
print(2 + 3 * 4)
Output
14

Common Interview Questions


1. Difference between / and //
print(10 / 3)
print(10 // 3)
Output
3.3333333333333335
3

2. Difference between == and is


a = [1, 2]
b = [1, 2]

print(a == b)
print(a is b)
Output
True
False

3. What does % do?


Returns the remainder.
print(17 % 5)
Output
2

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.

The next topic is Strings .


This is one of the most important Python topics because almost every coding interview involves string manipulation.

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.

Accessing Characters (Indexing)


Python uses 0-based indexing.
P y t h o n
0 1 2 3 4 5
s = "Python"

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"

print(a + " " + b)


Output
Hello World

Repetition
print("Hi" * 3)
Output
HiHiHi

Length
s = "Python"

print(len(s))
Output
6

Common String Methods


Upper
print("python".upper())
Output
PYTHON

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).

Common Interview Questions


Difference between find() and index()
• find() → Returns -1 if not found.
• index() → Raises ValueError if not found.

Why are strings immutable?


Immutability makes strings safer to share, allows certain optimizations, and lets them be used as dictionary keys.

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.

1. Print the first and last character of "Placement"


s = "Placement"

print(s[0])
print(s[-1])
Output
P
t

2. Reverse "Python" using slicing


s = "Python"

print(s[::-1])
Output
nohtyP

3. Count the number of 'a' characters in "banana"


s = "banana"

print([Link]("a"))
Output
3

4. Replace "Java" with "Python" in "I love Java"


s = "I love Java"

print([Link]("Java", "Python"))
Output
I love Python

5. Split "one,two,three" using ,


s = "one,two,three"

print([Link](","))
Output
['one', 'two', 'three']

6. Join ["AI", "ML", "Python"] with "-"


words = ["AI", "ML", "Python"]

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"]

c = [10, "Hello", 5.5, True]

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]

Common Interview Questions


Difference between append() and extend()
a = [1,2]
[Link]([3,4])

print(a)
Output
[1,2,[3,4]]
a = [1,2]
[Link]([3,4])
print(a)
Output
[1,2,3,4]

Difference between sort() and sorted()


sort() sorted()
Modifies original list Returns new sorted list
Works only on lists Works on any iterable

Difference between remove(), pop(), and del


• remove(value) → removes by value.
• pop(index) → removes by index and returns the removed element.
• del → deletes by index or the entire list.

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)

Most Important List Methods for Placements


• append()
• extend()
• insert()
• remove()
• pop()
• sort()
• sorted()
• reverse()
• count()
• index()
• copy()
• clear()
Master these methods, along with indexing, slicing, and list comprehensions, and you'll be well-prepared for Python coding
interviews.

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")

t3 = (10, "Hello", 3.5, True)

t4 = ()

Single Element Tuple


Wrong:
t = (10)

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

Common Interview Questions


Tuple vs List
List Tuple
Mutable Immutable
[] ()
More methods Only count() and index()
Slightly slower Slightly faster
Cannot be dictionary keys Can be dictionary keys (if immutable)

Why use a tuple?


• Data should not change.
• Faster than lists for fixed data.
• Can be used as dictionary keys (when containing only immutable elements).
Practice Questions
1.
t = (10,20,30)
print(t[1])
Output
20

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

Most Important Tuple Concepts for Placements


• Creating tuples
• Single-element tuple ((10,))
• Indexing & slicing
• Tuple packing & unpacking
• count()
• index()
• Immutability
• Tuple vs List (very common interview question)

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.

List (Mutable → Data Changes)


Use a list when items can be added, removed, or updated.
1. Shopping Cart
cart = ["Laptop", "Mouse"]
User adds:
[Link]("Keyboard")
Removes:
[Link]("Mouse")
Why list?
• Items change frequently.
2. Student Attendance
attendance = ["Alice", "Bob", "Charlie"]
Students come and go.

3. Chat Messages
messages = []
New messages keep getting appended.

4. LeetCode Problems Solved


solved = ["Two Sum", "Binary Search"]
As you solve more:
[Link]("Merge Intervals")

5. AI Dataset Images
images = ["[Link]", "[Link]"]
More images are added during preprocessing.

Tuple (Immutable → Fixed Data)


Use a tuple when the data should never change.
1. GPS Coordinates
location = (12.2958, 76.6394)
Latitude and longitude shouldn't be modified accidentally.

2. RGB Color
red = (255, 0, 0)
A color value is fixed.

3. Database Record ID
student = (101, "Bhargavi")
The ID should remain constant.

4. Days of the Week


days = (
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
)
Days don't change.

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"}

s3 = {10, "Hello", 3.5}

s4 = set()
Empty Set
s = {}
Output
<class 'dict'>
Correct:
s = set()

print(type(s))
Output
<class 'set'>

Duplicates are Removed


s = {10, 20, 20, 30, 10}

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.)

Common Interview Questions


Difference between remove() and discard()
remove() discard()
Raises KeyError if element not found No error

Difference between add() and update()


s = {1,2}
[Link](3)

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.

3. Remove Duplicate IDs


ids = [101,102,101,103]

unique_ids = set(ids)
Output
{101, 102, 103}

4. Common Skills Between Candidates


alice = {"Python", "Java", "SQL"}
bob = {"Python", "C++", "SQL"}

print(alice & bob)


Output
{'Python', 'SQL'}

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}

Most Important Set Methods for Placements


• add()
• update()
• remove()
• discard()
• pop()
• clear()
• union()
• intersection()
• difference()
• symmetric_difference()
Interview Tip
When should you use a set?
Use a set when:
• You need unique elements.
• You want fast membership checking (x in set).
• You need operations like union, intersection, or difference.
This is why sets are heavily used in coding interviews for problems involving duplicates, lookups, and common/unique elements.

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

Difference between [] and get()


student["cgpa"]
Output
KeyError
[Link]("cgpa")
Output
None

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

Key & Value


for key, value in [Link]():
print(key, value)
Output
name Bhargavi
age 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}

Common Interview Questions


Can keys be duplicated?
d={
"a":1,
"a":2
}

print(d)
Output
{'a': 2}
Latest value overwrites the previous one.

Can values be duplicated?


d={
"a":1,
"b":1
}

print(d)
Output
{'a': 1, 'b': 1}
Yes.

Can keys be lists?


d={
[1,2]:"hello"
}
Output
TypeError
Lists are mutable and cannot be keys.

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

Most Important Dictionary Methods for Placements


• get()
• keys()
• values()
• items()
• update()
• pop()
• copy()
• clear()

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

if age >= 18:


print("Eligible")
Output
Eligible

2. if-else
age = 15

if age >= 18:


print("Eligible")
else:
print("Not Eligible")
Output
Not Eligible

3. if-elif-else
marks = 85

if marks >= 90:


print("A")
elif marks >= 75:
print("B")
elif marks >= 50:
print("C")
else:
print("Fail")
Output
B

4. Nested if
age = 20
citizen = True

if age >= 18:


if citizen:
print("Can Vote")
Output
Can Vote

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

msg = "Adult" if age >= 18 else "Minor"

print(msg)
Output
Adult

7. match-case (Python 3.10+)


Similar to Java's switch.
day = 2

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

Loop through List


nums = [10,20,30]

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"]

for index, fruit in enumerate(fruits):


print(index, fruit)
Output
0 Apple
1 Banana
2 Mango
Starting index
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
Output
1 Apple
2 Banana
3 Mango

zip()
Combines multiple iterables.
names = ["Alice","Bob"]
marks = [90,95]

for name, mark in zip(names, marks):


print(name, mark)
Output
Alice 90
Bob 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.

Common Interview Questions


Difference between break, continue, pass
break continue pass
Exits loop Skips current iteration Does nothing

Difference between for and while


for while
Known number of iterations Unknown number of iterations
Uses iterable Uses condition

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"]

for i, fruit in enumerate(fruits):


print(i, fruit)

6.
a = [1,2,3]
b = ["A","B","C"]

for x, y in zip(a, b):


print(x, y)

Most Important Topics for Placements


• if, elif, else
• for
• while
• range()
• break
• continue
• enumerate()
• zip()
• match-case (know the syntax)
• pass (basic understanding)
These are the control flow concepts you'll use constantly in Python coding interviews and DSA solutions.

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

2. Function with Parameters


def greet(name):
print(f"Hello {name}")

greet("Bhargavi")
Output
Hello Bhargavi

3. Function with Return Value


def add(a, b):
return a + b

result = add(10, 20)

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]

result = list(map(lambda x:x*2, nums))

print(result)
Output
[2, 4, 6]

filter()
Filters elements.
nums = [1,2,3,4,5]

result = list(filter(lambda x:x%2==0, nums))

print(result)
Output
[2, 4]

reduce()
Need to import it.
from functools import reduce

nums = [1,2,3,4]

result = reduce(lambda a,b:a+b, nums)

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

Variable Number of Arguments


def fun(*args):
print(args)

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

Difference between return and print


return print
Sends value back Displays value
Ends function Doesn't end function
Can be stored Cannot be stored

Difference between *args and **kwargs


*args **kwargs
Positional arguments Keyword arguments
Tuple Dictionary

Difference between map(), filter(), reduce()


Function Purpose
map() Transform every element
filter() Keep elements matching a condition
reduce() Combine all elements into one value

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

Most Important for Placements


Focus on these:
• Function definition
• return
• Parameters vs Arguments
• Default Arguments
• Keyword Arguments
• *args
• **kwargs
• Lambda Functions
• map()
• filter()
• reduce()
• Recursion
• Scope (local vs global)
These are the function-related concepts most frequently asked in Python interviews and used in real-world code.

The next topic is Object-Oriented Programming (OOP)


This is one of the most frequently asked Python interview topics.
We'll cover it in this order:
1. Class
2. Object
3. Constructor (__init__)
4. self
5. Instance Variables
6. Instance Methods
7. Inheritance
8. Polymorphism
9. Encapsulation
10. Abstraction
11. Method Overloading (Python way)
12. Method Overriding
13. super()
14. Multiple Inheritance
15. MRO (Method Resolution Order)
16. @staticmethod
17. @classmethod

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

Constructor with Parameters


class Student:

def __init__(self, name, age):


[Link] = name
[Link] = age

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:

def __init__(self, name):


[Link] = name

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 __init__(self, name):


[Link] = name

def display(self):
print([Link])

s = Student("Bhargavi")

[Link]()
Output
Bhargavi

6. Instance Variables
class Student:

def __init__(self, name):


[Link] = name

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:

def __init__(self, brand):


[Link] = brand

c = Car("BMW")

print([Link])
Output
BMW

2.
class Student:

def __init__(self, name, cgpa):


[Link] = name
[Link] = cgpa

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.

Perfect! Now we start the most important OOP concept.


OOP Part 2 – Inheritance

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.

Why use Inheritance?


Without inheritance:
class Dog:
def eat(self):
print("Eating")

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.

Child with Its Own Constructor


class Animal:

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")

class Child(Father, Mother):


pass

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.

Why use inheritance?


To reuse existing code and avoid duplication.

Difference between Parent and Child?


Parent Child
Base class Derived class
Gives properties Inherits properties

Can a child access parent methods?


Yes.
Can a parent access child methods?
No.
Example:
class Animal:
pass

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")

class C(A, B):


pass

c = C()

[Link]()
[Link]()

Important Concepts to Remember


• Parent (Superclass/Base Class)
• Child (Subclass/Derived Class)
• Code Reusability
• Constructor inheritance
• isinstance()
• issubclass()
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance

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.

OOP Part 3 – Method Overriding & super()

What is Method Overriding?


Method overriding occurs when a child class provides its own implementation of a method that already exists in the parent
class.
Parent

show()


Child
show() ← overrides parent's show()

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.

What if the Child Doesn't Override?


class Animal:

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

Calling Parent Method


class Animal:

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

Passing Arguments to Parent Constructor


class Animal:

def __init__(self, name):


[Link] = name

class Dog(Animal):

def __init__(self, name, breed):


super().__init__(name)
[Link] = breed

dog = Dog("Bruno", "Labrador")

print([Link])
print([Link])
Output
Bruno
Labrador

super() in Multiple Inheritance


super() follows the Method Resolution Order (MRO).
class A:

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.

Method Overloading vs Method Overriding


Method Overloading Method Overriding
Same class Parent & Child
Same method name Same method name
Different parameters Same parameters
Python doesn't support traditional overloading Fully supported

Interview Questions
What is Method Overriding?
Redefining a parent's method in the child class with the same name and parameters.

Why use super()?


To access the parent class's methods and constructor.

Can we call the parent constructor without super()?


Yes, but it's not recommended.
Animal.__init__(self)
Preferred:
super().__init__()

Can we call both parent and child methods?


Yes.
super().method()

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

Important Interview Points


• Method Overriding = Child redefines parent's method.
• super() refers to the parent class.
• super().__init__() calls the parent constructor.
• super().method() calls the parent method.
• Overriding is a key part of runtime polymorphism.

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.

OOP Part 4 – Polymorphism


What is Polymorphism?
Polymorphism means "many forms."
• Poly = Many
• Morphism = Forms
The same method or operation behaves differently depending on the object.
Real-Life Example
Think of the start() operation.
Car -> Key Start
Bike -> Self Start
Bus -> Push Button
The operation is the same (start()), but the behavior is different.

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)

add(int a, int b, int c)


Python doesn't support traditional method overloading.
Example:
class Test:

def show(self):
print("First")

def show(self):
print("Second")

t = Test()
[Link]()
Output
Second
The second method replaces the first.

How Python Achieves Overloading


Using default arguments.
def add(a, b=0, c=0):
return a + b + c

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("Hello" + " World")


Output
Hello World

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

Does Python support method overloading?


Not traditionally.
Instead use:
• Default arguments
• *args

How is runtime polymorphism achieved?


Through method overriding.

What is Duck Typing?


Python focuses on an object's behavior (methods), not its type.

What is operator overloading?


Same operator performing different operations depending on the operand type.
Example:
10 + 20
"Hello" + "World"

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

Difference: Overloading vs Overriding


Method Overloading Method Overriding
Same class Parent & Child
Same method name Same method name
Different parameters Same parameters
Python uses default args / *args Fully supported
Compile-time concept Runtime concept

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.

Perfect! We've covered:


• Class & Object
• Constructor
• self
• Inheritance
• Method Overriding
• super()
• Polymorphism
Now comes another pillar of OOP.
OOP Part 5 – Encapsulation

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

Access Modifiers in Python


Python has three levels (by convention and name mangling):
Modifier Syntax Access
Public name Anywhere
Protected _name Inside class & subclasses (convention)
Private __name Inside the class (name mangling)

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.

Accessing Private Members


class Student:

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.

Getters and Setters


Instead of exposing variables directly, use methods.
class Student:

def __init__(self):
self.__age = 21

def get_age(self):
return self.__age

def set_age(self, age):


self.__age = age

s = Student()

print(s.get_age())

s.set_age(22)

print(s.get_age())
Output
21
22

Why Use Getters and Setters?


Suppose age shouldn't be negative.
class Student:

def __init__(self):
self.__age = 21

def set_age(self, age):

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.

Difference between Public, Protected and Private


Public Protected Private
name _name __name
Anywhere Convention: internal use Name mangling limits direct access

Does Python have true private variables?


Not exactly.
Python uses name mangling, not strict access control like Java or C++.

Why use getters and setters?


To validate and control 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.

Perfect! Now we'll learn the 4th pillar of OOP.


So far we've covered:
• Inheritance
• Polymorphism
• Encapsulation
• Abstraction ← Now

OOP Part 6 – Abstraction

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.

Child Must Implement It


from abc import ABC, abstractmethod

class Animal(ABC):

@abstractmethod
def sound(self):
pass

class Dog(Animal):

def sound(self):
print("Bark")

dog = Dog()

[Link]()
Output
Bark

What if Child Doesn't Implement?


from abc import ABC, abstractmethod

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.

Multiple Abstract Methods


from abc import ABC, abstractmethod

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.

Difference between Abstraction and Encapsulation


Abstraction Encapsulation
Hides implementation Hides data
Focuses on "What" Focuses on "How data is accessed"
Uses abstract classes Uses private/protected members
Achieved using ABC and @abstractmethod Achieved using __private, getters/setters

Can an Abstract Class Have Normal Methods?


Yes.
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 = Dog()

[Link]()
[Link]()
Output
Eating
Bark
Only sound() is abstract.

Interview Questions
What is abstraction?
Hiding implementation details while exposing only the essential functionality.

Can we create an object of an abstract class?


No.

Which module is used?


abc

Which decorator is used?


@abstractmethod

Can an abstract class have constructors?


Yes.
from abc import ABC

class A(ABC):

def __init__(self):
print("Constructor")

Can an abstract class have normal methods?


Yes.

Can an abstract class have instance variables?


Yes.

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

OOP Pillars Recap


Pillar Purpose
Inheritance Reuse code
Polymorphism One interface, many implementations
Encapsulation Protect and control data
Abstraction Hide implementation details

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.

First Understand This


When you create objects:
class Student:
pass

s1 = Student()
s2 = Student()
There are two kinds of variables:
Instance Variables
Each object has its own copy.
class Student:

def __init__(self, name):


[Link] = name
[Link] = "Bhargavi"

[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"

def __init__(self, name):


[Link] = name

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 __init__(self, name):


[Link] = name

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 __init__(self, name):


[Link] = name

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

When to Use What?


Instance Method
Needs object data.
Example
withdraw()

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:

def __init__(self, name):


[Link] = name

@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

Can a static method access instance variables?


No.

Can a class method access instance variables?


No.

Can an instance method access class variables?


Yes.
Example
class Student:

college = "VVCE"

def show(self):
print([Link])

Student().show()
Output
VVCE

Can an instance method call a static method?


Yes.
class A:

@staticmethod
def fun():
print("Hello")

def show(self):
[Link]()

A().show()
Output
Hello

Can a class method call a static method?


Yes.
class A:

@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 __init__(self, name):


[Link] = name

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

Easy Memory Trick


Imagine a college:
• Instance Method (self) → Talks about one student (name, age, CGPA).
• Class Method (cls) → Talks about the whole college (college name, principal).
• Static Method → Talks about neither; it's just a helper (e.g., grade calculation, email validation).

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.

You might also like