0% found this document useful (0 votes)
9 views44 pages

Core Python Concepts for Interviews

eng

Uploaded by

tanujb046
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)
9 views44 pages

Core Python Concepts for Interviews

eng

Uploaded by

tanujb046
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

Core Python Concepts

Here’s a comprehensive list of Core Python Concepts that are frequently asked in interviews
(beginner to intermediate level) 👇
🧠 Core Python Concepts for Interview
🔹 1. Basic Syntax & Fundamentals
Python keywords and identifiers
Indentation and comments

Variables and data types (int, float, str, bool, complex)

Type conversion and casting (int(), float(), str())

input() and print() functions

Operators: arithmetic, comparison, logical, assignment, bitwise

🔹 2. Control Flow Statements


if, elif, else

Nested conditions

Loops:

for loop

while loop

Loop control statements:

break

continue

pass

🔹 3. Functions
Function definition and calling
Function arguments: positional, keyword, default, variable-length (*args, **kwargs)

Return values
Scope of variables (local, global)

Lambda (anonymous) functions


Recursion

🔹 4. Data Structures
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/44
🧩 Built-in Collections:
List → mutable, ordered
Tuple → immutable, ordered

Set → unordered, unique elements


Dictionary → key-value pairs

🛠 Common Operations:
Indexing, slicing
Adding/removing elements

Sorting and searching


Iteration and comprehension

List comprehension
Dictionary comprehension

🔹 5. Strings
String creation and indexing

String methods (upper(), lower(), split(), replace(), find())


String formatting (f-strings, .format(), %)

String slicing and concatenation

🔹 6. File Handling
Opening and closing files (open(), close())

Reading and writing files (read(), readline(), write())


File modes: r, w, a, r+

with statement (context manager)

🔹 7. Exception Handling
try, except, else, finally blocks

Common exceptions (ValueError, TypeError, IOError, etc.)


Raising exceptions using raise

Creating custom exceptions

🔹 8. Object-Oriented Programming (OOP)


Class and object creation

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/44
__init__ constructor

Instance vs class vs static variables

Methods: instance, class, static


Inheritance (single, multiple, multilevel)

Polymorphism, Encapsulation, Abstraction

Method overriding and overloading

Special (magic/dunder) methods (__str__, __len__, __add__, etc.)

🔹 9. Modules and Packages


Importing modules (import, from ... import ...)

Built-in modules (math, random, os, datetime, sys)

Creating custom modules

Concept of __init__.py and packages

🔹 10. Advanced Core Topics


Iterators and Generators (iter(), next(), yield)

Decorators (@decorator_name)

List vs Generator comprehension

*args and **kwargs


Mutable vs Immutable objects

Shallow vs Deep copy (copy module)

🔹 11. Memory Management & Internals


Garbage collection

Reference counting
id() function and object references

Python’s memory model (stack & heap)

🔹 12. Important Built-in Functions


len(), type(), range(), enumerate(), zip(), map(), filter(), sorted(), sum(), any(), all(), min(), max(),
isinstance(), dir(), help()

🔹 13. Frequently Asked Interview Questions


1. Difference between list, tuple, and set

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/44
2. Explain shallow copy vs deep copy

3. What are mutable and immutable data types?


4. What is the difference between is and ==?
5. What are decorators and generators?

6. Difference between @staticmethod, @classmethod, and instance methods


7. What is pickling and unpickling in Python?
8. How does Python manage memory?

9. What is GIL (Global Interpreter Lock)?


10. What is the difference between deep copy and assignment operator (=)?

Would you like me to make this into a PDF interview cheat sheet (1–2 pages, neatly formatted)?
It can be useful for quick revision before interviews.

Here’s a clear explanation of Variables and Data Types in Python with syntax and examples 👇
🧩 1. Variables in Python
🔹 Definition:
A variable is a name that stores a value in memory.
You don’t need to declare its type explicitly — Python assigns it automatically.

🧠 Syntax:
python

variable_name = value

💡 Examples:
python

name = "Tanuj" # string


age = 21 # integer
height = 5.9 # float
is_student = True # boolean
number = 3 + 4j # complex number

🧮 2. Python Data Types with Syntax and Examples


Data Type Description Example Output Type
int Whole numbers (no decimal) a = 10 <class 'int'>
float Decimal numbers b = 3.14 <class 'float'>
str Sequence of characters (text) name = "Tanuj" <class 'str'>

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/44
Data Type Description Example Output Type

bool True or False values is_ready = True <class 'bool'>


complex Numbers with real and imaginary parts z = 2 + 3j <class 'complex'>

🔍 Example Code:
python

# Different Data Types


a = 10 # int
b = 3.14 # float
c = "Python" # str
d = True # bool
e = 2 + 3j # complex

# Display values and their types


print(a, type(a))
print(b, type(b))
print(c, type(c))
print(d, type(d))
print(e, type(e))

🖥️ Output:
python

10 <class 'int'>
3.14 <class 'float'>
Python <class 'str'>
True <class 'bool'>
(2+3j) <class 'complex'>

Would you like me to add a short exercise or question based on variables and data types next?

Here’s a clear and simple explanation of Type Conversion and Casting in Python with syntax and
examples 👇
🔄 Type Conversion and Casting
Python allows you to change the data type of a variable — this process is called type conversion (or
type casting).

🔹 1. Type Conversion
✅ Automatic (Implicit) Conversion — done by Python automatically.
✅ Explicit Conversion (Type Casting) — done manually using built-in functions.
🧠 1. Implicit Type Conversion
Python automatically converts one data type to another when needed, without losing data.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/44
💡 Example:
python

a = 5 # int
b = 2.5 # float

result = a + b # int + float → float


print(result)
print(type(result))

🖥️ Output:
javascript

7.5
<class 'float'>

📝 Python converted a (int) into a float automatically.

🧠 2. Explicit Type Conversion (Type Casting)


You manually change the type of data using built-in functions like:

int() → converts to integer


float() → converts to floating-point number

str() → converts to string

💡 Examples:
python

# Convert float to int


x = 3.9
y = int(x)
print(y, type(y)) # 3 <class 'int'>

# Convert int to float


a = 10
b = float(a)
print(b, type(b)) # 10.0 <class 'float'>

# Convert int to string


num = 100
s = str(num)
print(s, type(s)) # '100' <class 'str'>

# Convert string to int


text = "25"
val = int(text)
print(val + 5) # 30

⚠️ Invalid Conversion Example


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/44
python

s = "Hello"
num = int(s) # ❌ Error: cannot convert non-numeric string to int
🧩 You can only convert strings that contain numbers (e.g. "123") to int or float.

Would you like me to give a small exercise question next (like “convert given string and add numbers”)?

Here’s a clear explanation of if, elif, and else statements in Python with syntax and examples 👇
⚙️ Conditional Statements (if, elif, else)
These statements are used to make decisions in your Python program based on certain conditions.

🧠 1. Syntax:
python

if condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition2 is true
else:
# code to execute if all conditions are false

💡 2. Example 1: Checking a Number


python

num = 10

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

🖥️ Output:
typescript

Positive number

💡 3. Example 2: Checking Marks

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/44
python

marks = 85

if marks >= 90:


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

🖥️ Output:
css

Grade B

💡 4. Example 3: Even or Odd


python

num = 7

if num % 2 == 0:
print("Even number")
else:
print("Odd number")

🖥️ Output:
typescript

Odd number

⚠️ Notes:
Indentation (spaces or tabs) is very important in Python.

The elif stands for “else if”.


Only one block will execute even if multiple conditions are true.

Would you like me to give a short practice question next (like “check if a number is positive, negative,
or zero”) for you to try?

Here’s a simple and clear explanation of Nested Conditions in Python with syntax and examples 👇
🧠 Nested Conditions in Python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/44
A nested condition means using an if statement inside another if statement.
It helps when you need to check multiple levels of conditions.

🔹 Syntax:
python

if condition1:
if condition2:
# code runs if both condition1 and condition2 are true
else:
# code runs if condition1 is true but condition2 is false
else:
# code runs if condition1 is false

💡 Example 1: Check if a Number is Positive and Even


python

num = 8

if num > 0:
if num % 2 == 0:
print("The number is positive and even")
else:
print("The number is positive but odd")
else:
print("The number is not positive")

🖥️ Output:
csharp

The number is positive and even

💡 Example 2: Grading System with Nested Conditions


python

marks = 92

if marks >= 50:


print("You passed!")
if marks >= 90:
print("Excellent performance")
elif marks >= 75:
print("Good performance")
else:
print("Average performance")
else:
print("You failed.")

🖥️ Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/44
nginx

You passed!
Excellent performance

⚙️ Key Points:
You can nest any number of if statements inside each other.
Proper indentation is important.

Nested conditions make your logic more specific.

Would you like me to give a small practice question next (like checking if a number is positive,
negative, and even/odd together)?

Here’s a clear explanation of Loops in Python — both for loop and while loop — with syntax and
examples 👇
🔁 Loops in Python
Loops are used to repeat a block of code multiple times until a condition is met.

🧩 1. for loop
🔹 Definition:
The for loop is used to iterate over a sequence (like a list, tuple, string, or range of numbers).

🧠 Syntax:
python

for variable in sequence:


# code to execute for each item

💡 Example 1: Using range()


python

for i in range(1, 6):


print(i)

🖥️ Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/44
1
2
3
4
5

💡 Example 2: Looping through a List


python

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(fruit)

🖥️ Output:
nginx

apple
banana
cherry

💡 Example 3: Loop through String


python

for ch in "Python":
print(ch)

🖥️ Output:
css

P
y
t
h
o
n

🔁 2. while loop
🔹 Definition:
The while loop keeps running as long as a condition is true.

🧠 Syntax:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/44
python

while condition:
# code to execute repeatedly

💡 Example 1: Counting Numbers


python

i = 1
while i <= 5:
print(i)
i += 1

🖥️ Output:
1
2
3
4
5

💡 Example 2: Countdown
python

count = 5
while count > 0:
print(count)
count -= 1
print("Blast off!")

🖥️ Output:
vbnet

5
4
3
2
1
Blast off!

⚙️ Key Differences:
Feature for loop while loop
When you know how many times to When you don’t know the exact number of
Use case
run iterations
Syntax Iterates over a sequence Runs until condition becomes False

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/44
Feature for loop while loop
Control
Defined automatically Must be updated manually
variable

Would you like me to add loop control statements next (like break, continue, and pass) with examples?

Here’s a clear explanation of Loop Control Statements in Python — break, continue, and pass — with
syntax and examples 👇
🔁 Loop Control Statements
These statements let you control the flow of loops — i.e., stop, skip, or do nothing inside a loop.

🔹 1. break Statement
🧠 Purpose:
Used to exit (stop) the loop immediately, even if the loop condition is still true.

💡 Syntax:
python

for variable in sequence:


if condition:
break

💡 Example:
python

for i in range(1, 10):


if i == 5:
break
print(i)

🖥️ Output:
1
2
3
4

📝 The loop stops when i becomes 5.

🔹 2. continue Statement
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/44
🧠 Purpose:
Used to skip the current iteration and move to the next one.

💡 Syntax:
python

for variable in sequence:


if condition:
continue

💡 Example:
python

for i in range(1, 6):


if i == 3:
continue
print(i)

🖥️ Output:
1
2
4
5

📝 The loop skips printing 3 and continues.

🔹 3. pass Statement
🧠 Purpose:
Used as a placeholder — it does nothing, but allows code to run without an error.
It’s useful when you’re writing code that you’ll complete later.

💡 Syntax:
python

for variable in sequence:


if condition:
pass

💡 Example:
python

for i in range(1, 6):


if i == 3:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/44
pass # to be filled later
print(i)

🖥️ Output:
1
2
3
4
5

📝 pass does nothing — it’s just a “do nothing” statement.

🧾 Summary Table
Statement Meaning Effect on Loop
break Exit the loop completely Stops the loop
continue Skip current iteration Goes to next iteration
pass Do nothing Placeholder (no effect)

Would you like me to give a practice exercise next (using break, continue, and pass together)?

Here’s a simple and clear explanation of Function Definition and Calling in Python with syntax and
examples 👇
🧩 Functions in Python
🔹 Definition:
A function is a block of reusable code that performs a specific task.
It helps make your program modular, readable, and reusable.

🧠 1. Function Definition
You define a function using the def keyword.

Syntax:

python

def function_name(parameters):
# block of code
return value

🧠 2. Function Calling
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/44
Once defined, you can call (use) the function by writing its name followed by parentheses ().

Syntax:

python

function_name(arguments)

💡 Example 1: Function without Parameters


python

def greet():
print("Hello, welcome to Python!")

# Function call
greet()

🖥️ Output:
css

Hello, welcome to Python!

💡 Example 2: Function with Parameters


python

def add(a, b):


result = a + b
print("Sum =", result)

# Function call
add(5, 10)

🖥️ Output:
ini

Sum = 15

💡 Example 3: Function with Return Value


python

def multiply(x, y):


return x * y

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/44
product = multiply(4, 6)
print("Product =", product)

🖥️ Output:
ini

Product = 24

💡 Example 4: Function with Default Argument


python

def greet(name="Guest"):
print("Hello,", name)

greet("Tanuj") # with argument


greet() # without argument

🖥️ Output:
Hello, Tanuj
Hello, Guest

⚙️ Key Points
def keyword is used to define a function.
return keyword sends back a value (optional).
Functions must be called after definition.

You can define functions with or without parameters.

Would you like me to explain types of function arguments next (like positional, keyword, default, and
variable-length *args, **kwargs)?

Here’s a clear explanation of Function Arguments in Python — covering positional, keyword, default,
and variable-length (*args, **kwargs) — with syntax and examples 👇
🧠 Function Arguments in Python
When you define a function, you can pass values (arguments) to it.
Python supports different types of arguments to make functions flexible.

🔹 1. Positional Arguments
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/44
🧩 Definition:
Values are passed in order — the position of each argument matters.

Syntax:

python

def function_name(arg1, arg2):


# code

💡 Example:
python

def greet(name, age):


print("Name:", name)
print("Age:", age)

greet("Tanuj", 21)

🖥️ Output:
makefile

Name: Tanuj
Age: 21

📝 The first value goes to name, the second to age.

🔹 2. Keyword Arguments
🧩 Definition:
You specify which parameter gets which value by using the parameter name during the call.

Syntax:

python

function_name(param1=value1, param2=value2)

💡 Example:
python

def greet(name, age):


print("Name:", name)
print("Age:", age)

greet(age=21, name="Tanuj")

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/44
🖥️ Output:
makefile

Name: Tanuj
Age: 21

📝 Order doesn’t matter here, since keywords are used.


🔹 3. Default Arguments
🧩 Definition:
You can give default values to parameters.
If no argument is provided, the default value is used.

Syntax:

python

def function_name(param=value):
# code

💡 Example:
python

def greet(name="Guest"):
print("Hello,", name)

greet("Tanuj") # uses provided value


greet() # uses default value

🖥️ Output:
Hello, Tanuj
Hello, Guest

🔹 4. Variable-Length Arguments
Sometimes you don’t know how many arguments will be passed.
You can use *args and **kwargs to handle this.

🧩 *(a) args — Non-keyword Variable Arguments


Used to pass multiple positional arguments.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/44
Syntax:

python

def function_name(*args):
# args is a tuple

💡 Example:
python

def add_numbers(*args):
total = 0
for num in args:
total += num
print("Sum =", total)

add_numbers(2, 4, 6)
add_numbers(1, 2, 3, 4, 5)

🖥️ Output:
ini

Sum = 12
Sum = 15

🧩 **(b) kwargs — Keyword Variable Arguments


Used to pass multiple keyword arguments (key=value pairs).

Syntax:

python

def function_name(**kwargs):
# kwargs is a dictionary

💡 Example:
python

def show_details(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")

show_details(name="Tanuj", age=21, course="Python")

🖥️ Output:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/44
makefile

name: Tanuj
age: 21
course: Python

🧾 Summary Table
Type Symbol Description Example
Positional – Values passed in order add(2, 3)

Keyword – Pass using key=value add(a=2, b=3)


Default – Uses default value if not passed def add(a=5)
Variable-length *args Many positional args → tuple add(1,2,3)

Variable-length **kwargs Many keyword args → dict info(name="Tanuj")

Would you like me to explain return statement and scope of variables (local vs global) next?

Here’s a clear and simple explanation of Return Values in Python functions with syntax and examples
👇
🔙 Return Values in Python
🔹 Definition:
The return statement is used inside a function to send a result (value) back to the place where the
function was called.
If no return is used, the function returns None by default.

🧠 Syntax:
python

def function_name(parameters):
# some code
return value

💡 Example 1: Function Returning a Value


python

def add(a, b):


return a + b

result = add(5, 7)
print("Sum =", result)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/44
🖥️ Output:
ini

Sum = 12

📝 The function add() returns the value of a + b, which is stored in result.

💡 Example 2: Function Returning Multiple Values


You can return multiple values as a tuple.

python

def calculate(a, b):


sum_ = a + b
diff = a - b
return sum_, diff

x, y = calculate(10, 4)
print("Sum =", x)
print("Difference =", y)

🖥️ Output:
ini

Sum = 14
Difference = 6

💡 Example 3: Function Without Return


python

def greet(name):
print("Hello,", name)

result = greet("Tanuj")
print(result)

🖥️ Output:
css

Hello, Tanuj
None

📝 Since there’s no return, Python automatically returns None.

💡 Example 4: Using Return in Conditional Logic


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/44
python

def check_number(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"

print(check_number(7))
print(check_number(10))

🖥️ Output:
nginx

Odd
Even

⚙️ Key Points
return ends the function immediately.
You can return any data type — number, string, list, tuple, etc.
If no return statement is given, the function returns None.

Would you like me to explain local and global variables (scope) next?

Here’s a clear and easy explanation of Scope of Variables in Python — covering Local and Global scope
with syntax and examples 👇
🌍 Scope of Variables in Python
The scope of a variable determines where in the program the variable can be accessed or modified.
Python has two main types of variable scopes:

Local Variables
Global Variables

🔹 1. Local Variables
🧠 Definition:
A local variable is defined inside a function and can only be used within that function.

Syntax:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/44
python

def function_name():
local_var = value # local scope
# use local_var here only

💡 Example:
python

def my_function():
message = "Hello from inside the function!" # local variable
print(message)

my_function()


# Trying to access message outside will cause an error
# print(message)

🖥️ Output:
javascript

Hello from inside the function!

📝 You cannot access message outside the function because it’s local to my_function().

🔹 2. Global Variables
🧠 Definition:
A global variable is defined outside any function and can be used anywhere in the program.

Syntax:

python

global_var = value # global scope

def function_name():
print(global_var)

💡 Example:
python

name = "Tanuj" # global variable

def show_name():
print("Inside function:", name)

show_name()
print("Outside function:", name)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/44
🖥️ Output:
bash

Inside function: Tanuj


Outside function: Tanuj

📝 The global variable name is accessible inside and outside the function.

🔹 3. Modifying Global Variables Inside a Function


If you want to change a global variable inside a function,
you must use the global keyword.

💡 Example:
python

count = 0 # global variable

def increase():
global count # declare that we are using the global 'count'
count += 1
print("Inside function:", count)

increase()
print("Outside function:", count)

🖥️ Output:
bash

Inside function: 1
Outside function: 1

📝 Without the global keyword, Python would create a new local variable named count.

🔹 4. Local vs Global — Example Together


python

x = 10 # global variable

def test():
x = 5 # local variable (different from global x)
print("Inside function:", x)

test()
print("Outside function:", x)

🖥️ Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/44
bash

Inside function: 5
Outside function: 10

📝 The local x inside the function does not affect the global x.

🧾 Summary Table
Type Declared Accessible Keyword Needed?
Local Variable Inside a function Only inside that function ❌ No
Global Outside all Everywhere in the ✅ Use global to modify inside a
Variable functions program function

Would you like me to continue with the next topic — Lambda (anonymous) functions?

Perfect 👍
— Let’s cover both Lambda (anonymous) functions and Recursion clearly with syntax,
explanation, and examples 👇
⚡ Lambda (Anonymous) Functions
🧠 Definition:
A lambda function is a small, anonymous (unnamed) function in Python.
It is used for short, one-line functions where defining a full function using def would be unnecessary.

🧩 Syntax:
python

lambda arguments: expression

✅ The expression is automatically returned — no need for a return keyword.

💡 Example 1: Simple Addition


python

add = lambda a, b: a + b
print(add(5, 3))

🖥️ Output:
8

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/44
💡 Example 2: Square of a Number
python

square = lambda x: x ** 2
print(square(6))

🖥️ Output:
36

💡 Example 3: Using Lambda with map()

python

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)

🖥️ Output:
csharp

[1, 4, 9, 16, 25]

💡 Example 4: Using Lambda with filter()

python

nums = [10, 15, 20, 25, 30]


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

🖥️ Output:
csharp

[10, 20, 30]

✅ Use Case Summary:


Function Description Example
map() Apply a function to all items map(lambda x: x*2, data)
filter() Filter items by condition filter(lambda x: x>0, data)
sorted() Sort using key sorted(data, key=lambda x: x[1])

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/44
🔁 Recursion
🧠 Definition:
Recursion is when a function calls itself to solve a smaller instance of the same problem.
Every recursive function must have:

1. Base case – to stop recursion.


2. Recursive call – to solve smaller problems.

🧩 Syntax:
python

def function_name(parameters):
if base_condition:
return value
else:
return function_name(modified_parameters)

💡 Example 1: Factorial using Recursion


python

def factorial(n):
if n == 0 or n == 1: # base case
return 1
else:
return n * factorial(n - 1) # recursive call

print(factorial(5))

🖥️ Output:
120

💡 Example 2: Fibonacci Series using Recursion


python

def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)

for i in range(6):
print(fibonacci(i), end=" ")

🖥️ Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/44
0 1 1 2 3 5

⚠️ Note:
Recursive functions can cause a RecursionError if they call themselves too many times (no base case).

✅ Comparison: Recursion vs Iteration


Feature Recursion Iteration
Uses Function calls itself Uses loops
Stops when Base condition met Condition false
Memory use More (stack frames) Less

Example factorial(n-1) for loop

Would you like me to continue with Modules and Packages next?

Perfect 👍 Here’s a clear explanation of all four important Python data structures — List, Tuple, Set,
and Dictionary — with syntax, properties, and examples 👇
🧱 1. List → Mutable, Ordered
🧠 Definition:
A list is an ordered, mutable (changeable) collection of elements.
You can store different data types in a list.

🧩 Syntax:
python

my_list = [element1, element2, element3, ...]

💡 Example:
python

fruits = ["apple", "banana", "cherry"]


print(fruits) # Output: ['apple', 'banana', 'cherry']
print(fruits[1]) # Access → 'banana'

# Modify
fruits[1] = "mango"
print(fruits) # Output: ['apple', 'mango', 'cherry']

# Add & Remove


[Link]("orange")

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 29/44
[Link]("apple")
print(fruits) # Output: ['mango', 'cherry', 'orange']

✅ Key Features:
Ordered (maintains insertion order)
Mutable (can change values)

Allows duplicates

🪶 2. Tuple → Immutable, Ordered


🧠 Definition:
A tuple is like a list, but immutable — once created, elements cannot be changed.

🧩 Syntax:
python

my_tuple = (element1, element2, element3, ...)

💡 Example:
python

colors = ("red", "green", "blue")


print(colors) # Output: ('red', 'green', 'blue')
print(colors[0]) # Output: red

# colors[0] = "yellow" ❌
# Trying to change will cause an error
TypeError

✅ Key Features:
Ordered
Immutable (cannot be modified)
Allows duplicates
Faster than lists (for read-only data)

🌿 3. Set → Unordered, Unique Elements


🧠 Definition:
A set is an unordered collection of unique elements.
Used to remove duplicates or perform set operations like union/intersection.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 30/44
🧩 Syntax:
python

my_set = {element1, element2, element3, ...}

💡 Example:
python

numbers = {1, 2, 3, 3, 4}
print(numbers) # Output: {1, 2, 3, 4} (no duplicates)

[Link](5)
[Link](2)
print(numbers) # Output: {1, 3, 4, 5}

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print([Link](set2)) # {1, 2, 3, 4, 5}
print([Link](set2)) # {3}

✅ Key Features:
Unordered (no indexing)
Mutable (can add/remove elements)

Unique elements only

🔑 4. Dictionary → Key-Value Pairs


🧠 Definition:
A dictionary stores data in key-value pairs.
Keys are unique; values can be of any type.

🧩 Syntax:
python

my_dict = {key1: value1, key2: value2, key3: value3}

💡 Example:
python

student = {
"name": "Tanuj",
"age": 21,
"course": "Python"
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 31/44
print(student["name"]) # Output: Tanuj

# Modify
student["age"] = 22

# Add new key-value pair


student["grade"] = "A"

# Remove a key
del student["course"]

print(student)

🖥️ Output:
bash

{'name': 'Tanuj', 'age': 22, 'grade': 'A'}

✅ Key Features:
Key-value storage
Keys must be unique and immutable (e.g., string, int)
Values can be any type
Mutable and unordered (insertion order preserved in Python 3.7+)

📘 Quick Comparison Table


Type Ordered Mutable Allows Duplicates Syntax Example
List ✅ Yes ✅ Yes ✅ Yes [1, 2, 3]
Tuple ✅ Yes ❌ No ✅ Yes (1, 2, 3)
Set ❌ No ✅ Yes ❌ No {1, 2, 3}
Dictionary ✅ Yes (3.7+) ✅ Yes Keys ❌ {"a": 1, "b": 2}

Would you like me to continue with String operations (indexing, slicing, methods) next?

Excellent 👏You’re covering all core Python data manipulation concepts — these are very common in
interviews.
Let’s go through them step-by-step with syntax, examples, and key notes 👇
🔹 1. Indexing and Slicing
These are used to access parts of sequences — like lists, strings, or tuples.

🧩 Indexing:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 32/44
Access a single element using its index number.
(Index starts from 0)

python

numbers = [10, 20, 30, 40, 50]


print(numbers[0]) # Output: 10
print(numbers[-1]) # Output: 50 (last element)

🧩 Slicing:
Extract a range of elements using [start:end:step].

python

numbers = [10, 20, 30, 40, 50]


print(numbers[1:4]) # Output: [20, 30, 40]
print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[::2]) # Output: [10, 30, 50]

🧠 Remember:
start = inclusive
end = exclusive
Negative index counts from the end

🔹 2. Adding and Removing Elements


💡 List Example:
python

fruits = ["apple", "banana"]

# Add elements
[Link]("cherry") # Adds to end
[Link](1, "mango") # Insert at position 1
[Link](["orange", "kiwi"]) # Add multiple items
print(fruits)

🖥️ Output:
['apple', 'mango', 'banana', 'cherry', 'orange', 'kiwi']

💡 Removing elements
python

[Link]("banana") # Remove by value


[Link](2) # Remove by index
[Link]() # Remove all

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 33/44
🧠 Note:
remove() throws an error if element not found
pop() returns the removed element

🔹 3. Sorting and Searching


💡 Sorting
python

nums = [5, 3, 8, 1]
[Link]() # Ascending
print(nums) # [1, 3, 5, 8]

[Link](reverse=True) # Descending
print(nums) # [8, 5, 3, 1]

OR (without changing original list):

python

sorted_list = sorted(nums)

💡 Searching
python

nums = [10, 20, 30, 40]


print(20 in nums) # True
print([Link](30)) # 2

🧠 Note:
in keyword → checks existence
.index() → returns position of the first match

🔹 4. Iteration
💡 Using for loop:

python

fruits = ["apple", "banana", "cherry"]


for item in fruits:
print(item)

💡 Using enumerate() (to get index + value):

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 34/44
python

for i, fruit in enumerate(fruits):


print(i, fruit)

🖥️ Output:
0 apple
1 banana
2 cherry

🔹 5. Comprehensions
Comprehensions provide a compact way to create lists, sets, or dictionaries.

✅ List Comprehension
Syntax:

python

[new_item for item in iterable if condition]

Example 1:

python

squares = [x**2 for x in range(5)]


print(squares) # [0, 1, 4, 9, 16]

Example 2 (with condition):

python

even_nums = [x for x in range(10) if x % 2 == 0]


print(even_nums) # [0, 2, 4, 6, 8]

✅ Dictionary Comprehension
Syntax:

python

{key_expression: value_expression for item in iterable if condition}

Example:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 35/44
python

nums = [1, 2, 3, 4]
squares = {x: x**2 for x in nums}
print(squares)

🖥️ Output:
yaml

{1: 1, 2: 4, 3: 9, 4: 16}

Example with condition:

python

even_squares = {x: x**2 for x in range(10) if x % 2 == 0}


print(even_squares)

🖥️ Output:
yaml

{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

🧾 Summary Table
Operation Description Example
Indexing Access element by position list[2]
Slicing Extract range list[1:4]
Add append(), insert(), extend()

Remove remove(), pop(), clear()


Sort sort(), sorted()
Search in, index()
List Comprehension [x**2 for x in range(5)]
Dict Comprehension {x: x**2 for x in range(5)}

Would you like me to continue next with String Operations (indexing, slicing, methods like upper(),
replace(), etc.)?

Perfect 👍 Let’s now go over Strings — one of the most important Python concepts frequently asked in
interviews.
Here’s a clean explanation with syntax, examples, and notes 👇
💠 1. String Creation and Indexing
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 36/44
🧠 Definition:
A string is a sequence of characters enclosed in single (‘ ’), double (“ ”), or triple (“”“ ””“) quotes.

🧩 Syntax:
python

str1 = 'Hello'
str2 = "Python"
str3 = """This is
a multiline string."""

💡 Indexing Example:
python

word = "Python"
print(word[0]) # 'P' (first character)
print(word[-1]) # 'n' (last character)

🧠 Remember:
Indexing starts from 0

Negative indexing counts from the end

💠 2. String Methods
Python provides many built-in methods to manipulate strings.
Here are the most used ones:

🔹 upper()
Converts all characters to uppercase.

python

text = "hello"
print([Link]()) # Output: HELLO

🔹 lower()
Converts all characters to lowercase.

python

text = "HELLO"
print([Link]()) # Output: hello

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 37/44
🔹 split()
Splits the string into a list of words (default delimiter = space).

python

text = "Python is fun"


print([Link]()) # Output: ['Python', 'is', 'fun']

text2 = "apple,banana,orange"
print([Link](',')) # Output: ['apple', 'banana', 'orange']

🔹 replace()
Replaces part of the string with another string.

python

text = "I love Java"


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

🔹 find()
Returns the index of the first occurrence of a substring.

python

text = "Learning Python"


print([Link]("Python")) # Output: 9
print([Link]("Java")) # Output: -1 (not found)

💠 3. String Formatting
Formatting allows you to insert variables into strings neatly.

🔹 (a) f-Strings (Python 3.6+)


python

name = "Tanuj"
age = 21
print(f"My name is {name} and I am {age} years old.")

🖥️ Output:
pgsql

My name is Tanuj and I am 21 years old.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 38/44
🔹 (b) .format() Method

python

name = "Tanuj"
age = 21
print("My name is {} and I am {} years old.".format(name, age))

🖥️ Output:
pgsql

My name is Tanuj and I am 21 years old.

You can also use index positions:

python

print("I like {1} and {0}".format("Java", "Python"))


# Output: I like Python and Java

🔹 (c) % Formatting (Old Style)

python

name = "Tanuj"
age = 21
print("My name is %s and I am %d years old." % (name, age))

🖥️ Output:
pgsql

My name is Tanuj and I am 21 years old.

✅ → string

%s
%d → integer
✅ %f → float

💠 4. String Slicing and Concatenation


🔹 Slicing
Extract part of a string using [start:end:step].

python

text = "PythonProgramming"
print(text[0:6]) # 'Python'

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 39/44
print(text[6:]) # 'Programming'
print(text[::-1]) # 'gnimmargorPnohtyP' (reverse)

🔹 Concatenation
Combine multiple strings using + or join().

python

str1 = "Hello"
str2 = "World"
print(str1 + " " + str2) # Output: Hello World

words = ["Python", "is", "awesome"]


print(" ".join(words)) # Output: Python is awesome

🧾 Summary Table
Operation Description Example Output
Indexing Access char by index "Python"[1] 'y'
Slicing Substring extraction "Python"[0:3] 'Pyt'
upper() Uppercase "abc".upper() 'ABC'

lower() Lowercase "ABC".lower() 'abc'


split() Split into list "a,b,c".split(',') ['a','b','c']
replace() Replace substring "I love C".replace("C","Python") 'I love Python'
find() Find index "abc".find('b') 1
f-string Inline formatting f"{x} + {y}" '10 + 20'
Concatenation Combine "Hi" + "There" 'HiThere'

Would you like me to continue next with File Handling (open, read, write, close) or Exception
Handling (try-except, finally, raise)?

Excellent 👍
— File Handling is another must-know Python interview topic, especially for practical
coding rounds.
Here’s a complete and clear explanation with syntax, examples, and outputs 👇
📂 File Handling in Python
File handling allows you to read from and write to files stored on your computer.
Python provides built-in functions like open(), read(), write(), and close() to handle files safely.

🔹 1. Opening and Closing Files


🧠 Syntax:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 40/44
python

file_object = open("filename", "mode")


# perform file operations
file_object.close()

"filename" → name/path of the file


"mode" → how the file should be opened (read/write/etc.)

💡 Example:
python

file = open("[Link]", "w") # open in write mode


[Link]("Hello, Python File Handling!")
[Link]() # close the file

✅ Always close the file after operations to save memory and avoid data loss.
🔹 2. Reading and Writing Files
There are several ways to read file content:

(a) read() — Read entire file

python

file = open("[Link]", "r")


data = [Link]()
print(data)
[Link]()

🖥️ Output:
arduino

Hello, Python File Handling!

(b) readline() — Read one line at a time

python

file = open("[Link]", "r")


line1 = [Link]()
print(line1)
[Link]()

(c) readlines() — Read all lines into a list

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 41/44
python

file = open("[Link]", "r")


lines = [Link]()
print(lines)
[Link]()

🖥️ Output:
css

['Hello, Python File Handling!\n', 'This is line 2.\n']

(d) write() — Write text to file

python

file = open("[Link]", "w")


[Link]("This overwrites existing content.\n")
[Link]("New line added.")
[Link]()

(e) writelines() — Write multiple lines

python

lines = ["Python\n", "is\n", "fun!\n"]


file = open("[Link]", "w")
[Link](lines)
[Link]()

🔹 3. File Modes
Mode Description Creates New File? Overwrites?
'r' Read (default mode) ❌ No ❌ No
'w' Write ✅ Yes ✅ Yes
'a' Append ✅ Yes ❌ No (adds at end)
'r+' Read and Write ❌ No ❌ No (edits existing file)
💡 Examples of File Modes
Write Mode (w)

python

f = open("[Link]", "w")
[Link]("This is write mode.")
[Link]()

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 42/44
Append Mode (a)

python

f = open("[Link]", "a")
[Link]("\nThis line is appended.")
[Link]()

Read Mode (r)

python

f = open("[Link]", "r")
print([Link]())
[Link]()

Read + Write (r+)

python

f = open("[Link]", "r+")
print([Link]()) # Read content
[Link]("\nExtra line!") # Add new content
[Link]()

🔹 4. with Statement (Context Manager)


🧠 Definition:
Using with automatically opens and closes the file — even if an error occurs.
This is the recommended and safe method.

💡 Example:
python

with open("[Link]", "r") as file:


data = [Link]()
print(data)
# file automatically closed here

🧠 No need for [Link]().


The with block ensures automatic cleanup.

🧾 Summary Table
Operation Function Example

Open a file open("[Link]", "r") Opens in read mode


Read all read() Reads entire file

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 43/44
Operation Function Example
Read line readline() Reads one line
Read all lines readlines() Returns list of lines
Write write("text") Writes to file

Write multiple writelines(list) Writes multiple lines


Close close() Closes the file
Auto close with open(...) as f: Context manager

✅ Best Practice:
Always use with open() for file operations — it’s cleaner, safer, and preferred in interviews.

Would you like me to continue next with Exception Handling (try, except, else, finally, raise)?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 44/44

You might also like