KEMBAR78
Python Interview Preparation | PDF | Python (Programming Language) | Parameter (Computer Programming)
0% found this document useful (0 votes)
27 views22 pages

Python Interview Preparation

The document provides a comprehensive guide for Python interview preparation, covering essential topics from basic to advanced levels, including data types, control structures, OOP, and libraries relevant for AI roles. It emphasizes the importance of understanding Python fundamentals, problem-solving techniques, and efficient coding practices. Additionally, it lists expected interview questions and detailed answers to common queries about Python features and functionalities.
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)
27 views22 pages

Python Interview Preparation

The document provides a comprehensive guide for Python interview preparation, covering essential topics from basic to advanced levels, including data types, control structures, OOP, and libraries relevant for AI roles. It emphasizes the importance of understanding Python fundamentals, problem-solving techniques, and efficient coding practices. Additionally, it lists expected interview questions and detailed answers to common queries about Python features and functionalities.
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
You are on page 1/ 22

Python Interview Preparation (Basic →

Advanced)

1. Basics of Python (Foundations you must know)


These are non-negotiable — every Python interview starts here.

a. Python Introduction

• Python is an interpreted, high-level, object-oriented language.


• Used in AI, ML, Web Dev, Data Science, Automation, etc.
• Features: Easy syntax, dynamic typing, huge library support.

b. Data Types

• Numbers → int, float, complex.


• String → "Hello" (immutable).
• Boolean → True/False.
• None → Absence of value.
• Collections:
o list → ordered, mutable ([1,2,3])
o tuple → ordered, immutable ((1,2,3))
o set → unordered, unique ({1,2,3})
o dict → key-value ({"name": "Pratham"})

Example:

data = [1, 2, 3]
data.append(4) # list is mutable
name = "AI"
# name[0] = 'a' → ❌ Strings are immutable

c. Variables and Operators

• Variables: No type declaration needed.


• Operators:
o Arithmetic (+ - * / // % **)
o Comparison (== != < > <= >=)
o Logical (and, or, not)
o Identity (is, is not)
o Membership (in, not in)

d. Conditional Statements
x = 10
if x > 5:
print("Greater")
elif x == 5:
print("Equal")
else:
print("Smaller")

e. Loops

• for → iterate over sequence.


• while → repeat until condition false.
• break, continue, pass.

Example (Sum of list):

nums = [1,2,3,4]
total = 0
for n in nums:
total += n
print(total)

f. Functions

• Defined with def, supports parameters, return values.


• Default arguments, keyword arguments, *args, **kwargs.

Example:

def greet(name="User"):
return f"Hello {name}"
print(greet("Pratham"))

2. Intermediate Python (Most asked in interviews)


Now we go beyond syntax — focus on problem-solving & efficiency.
a. String Manipulation

• Common methods: .upper(), .lower(), .strip(), .split(), .join(), .replace().


• Slicing: s[0:5], s[::-1] (reverse).

Example:

s = "machine learning"
print(s.title()) # Machine Learning
print(s[::-1]) # gninrael enihcam

b. List & Dictionary Comprehensions


nums = [x**2 for x in range(5)] # [0,1,4,9,16]
squares = {x: x**2 for x in range(3)} # {0:0,1:1,2:4}

Interviewers love comprehensions for clean code.

c. File Handling
with open("data.txt", "r") as f:
content = f.read()

Modes: r, w, a, rb, wb.

d. Exception Handling
try:
print(5/0)
except ZeroDivisionError as e:
print("Error:", e)
finally:
print("Done")

e. Object-Oriented Programming (OOPs)

1. Class & Object


2. Inheritance (Single, Multiple, Multilevel)
3. Encapsulation (private vars using _var)
4. Polymorphism (method overriding, overloading)
Example:

class Animal:
def speak(self): print("Some sound")
class Dog(Animal):
def speak(self): print("Bark")
d = Dog()
d.speak() # Bark

f. Iterators & Generators

• Iterator → object with __iter__() & __next__().


• Generator → function with yield, saves memory.

Example:

def gen():
for i in range(3):
yield i
for x in gen():
print(x)

g. Modules & Packages

• Importing: import math, from math import sqrt.


• Creating custom modules (.py files).

h. Virtual Environments & pip

• Used for project dependency isolation.


• Commands:
o python -m venv env
o pip install numpy

3. Advanced Python (Important for AI roles)


These are high-level features and AI-focused libraries.

a. Decorators
• Functions that modify other functions.
Example:

def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper

@decorator
def hello():
print("Hello AI")
hello()

b. Context Managers

• Use with statement for resource management.

c. Multithreading & Multiprocessing

• Threading → concurrent tasks (I/O bound).


• Multiprocessing → true parallelism (CPU bound).

d. Python Libraries for AI/DS

• NumPy → Arrays, math operations.


• Pandas → Data analysis, DataFrames.
• Matplotlib / Seaborn → Visualization.
• Scikit-learn → ML algorithms.
• TensorFlow / PyTorch → Deep learning.

Example with NumPy:

import numpy as np
arr = np.array([1,2,3])
print(arr.mean()) # 2.0

e. Regular Expressions (Regex)

• Powerful for pattern matching.


import re
print(re.findall(r"\d+", "Age 23, ID 456")) # ['23','456']

f. Lambda, Map, Filter, Reduce


nums = [1,2,3,4]
print(list(map(lambda x: x**2, nums))) # [1,4,9,16]
print(list(filter(lambda x: x%2==0, nums))) # [2,4]

g. Memory Management

• Python uses garbage collection (reference counting + GC).


• Concepts: id(), is, mutability vs immutability.

h. Design Patterns (Optional but good)

• Singleton, Factory, Observer — sometimes asked in advanced interviews.

Expected Interview Questions (Python AI role)


1. Difference between list, tuple, and set?
2. Explain mutable vs immutable in Python with examples.
3. What are Python decorators? Give an example.
4. How does Python manage memory?
5. Explain iterators vs generators.
6. Difference between is and ==.
7. Explain NumPy arrays vs Python lists.
8. How would you handle missing values in Pandas?
9. Explain shallow copy vs deep copy in Python.
10. How would you optimize Python code for performance?

Of course Let’s go deeper into Python fundamentals — I’ll expand with more detail and
additional topics that are often asked in interviews. Since you’re preparing for an AI role,
they’ll expect your Python foundation to be solid.
Python Fundamentals (Expanded &
Detailed)
1. Variables & Data Types

• Variables are used to store values, and Python automatically detects the type (dynamic
typing).
• Data types include:
o Numeric: int, float, complex
o Boolean: True, False
o Sequence: list, tuple, range
o String: str
o Set Types: set, frozenset
o Mapping: dict
• Example:
• x = 10 # int
• y = 3.14 # float
• z = "AI" # str
• l = [1, 2, 3] # list

2. Operators

• Arithmetic: +, -, *, /, %, //, **
• Comparison: ==, !=, <, >, <=, >=
• Logical: and, or, not
• Bitwise: &, |, ^, ~, <<, >>
• Membership: in, not in
• Identity: is, is not
• Example:
• 5 // 2 # 2 (floor division)
• 2 ** 3 # 8 (power)

3. Strings & String Methods

• Strings are immutable sequences of characters.


• Useful methods:
o upper(), lower(), title()
o strip(), replace()
o split(), join()
o find(), count()
• Example:
• text = " Hello AI "
• print(text.strip().upper()) # "HELLO AI"

4. Lists

• Ordered, mutable, allows duplicates.


• Useful methods: append(), extend(), insert(), remove(), pop(), sort(),
reverse().
• List comprehension (very common in interviews):
• nums = [1, 2, 3, 4]
• squares = [x**2 for x in nums]

5. Tuples

• Ordered, immutable, faster than lists.


• Example:
• t = (1, 2, 3)

6. Dictionaries

• Key-value pairs, mutable, unordered (but insertion-ordered since Python 3.7).


• Methods: keys(), values(), items(), get(), update().
• Example:
• student = {"name": "Pratham", "course": "AI"}
• print(student["name"])

7. Sets

• Unordered collection, unique elements, mutable.


• Supports operations like union, intersection, difference.
• Example:
• a = {1, 2, 3}
• b = {3, 4, 5}
• print(a.union(b)) # {1,2,3,4,5}

8. Control Structures

• If-Else:
• if x > 0:
• print("Positive")
• elif x == 0:
• print("Zero")
• else:
• print("Negative")
• Loops:
o for → iterate over sequences
o while → repeat until condition fails
• Loop control: break, continue, pass

9. Functions

• Defined with def, can have default, variable, or keyword arguments.


• Example:
• def greet(name="Guest"):
• return f"Hello, {name}"
• Lambda functions: Anonymous functions.
• square = lambda x: x**2

10. Modules & Packages

• Module: A .py file with code you can import.


• Package: A collection of modules with __init__.py.
• Example:
• import math
• print(math.sqrt(16)) # 4.0

11. File Handling

• Reading/Writing files with open().


• Modes: r, w, a, rb, wb.
• Example:
• with open("data.txt", "w") as f:
• f.write("Hello AI")

12. Error Handling

• Use try-except-finally.
• Example:
• try:
• num = int("abc")
• except ValueError:
• print("Invalid number")
• finally:
• print("Done")

13. Object-Oriented Programming (OOP)

• Concepts:
o Class & Object
o Inheritance
o Encapsulation
o Polymorphism
• Example:
• class Animal:
• def speak(self):
• print("Sound")

• class Dog(Animal):
• def speak(self):
• print("Bark")

14. Iterators & Generators

• Iterator: Object implementing __iter__() & __next__().


• Generator: Uses yield, memory-efficient.
• Example:
• def count_up_to(n):
• i = 1
• while i <= n:
• yield i
• i += 1

15. Decorators

• Functions that modify other functions.


• Example:
• def decorator(func):
• def wrapper():
• print("Before function")
• func()
• print("After function")
• return wrapper

• @decorator
• def hello():
• print("Hello AI")
16. Virtual Environments & Package Management

• venv isolates Python environments.


• pip install package_name for installing dependencies.

17. Pythonic Features

• List comprehension
• with statement (context managers)
• Multiple assignment:
• a, b = 5, 10
• Unpacking:
• x, *y = [1, 2, 3, 4]

Perfect This is an excellent list — looks like your interviewers are covering Python
fundamentals + OOP + advanced Python concepts + ML/AI basics.

Detailed Answers to Your Questions

1. Python Virtual Machine (PVM)

• Python code is first compiled into bytecode (.pyc).


• This bytecode is executed by the Python Virtual Machine (PVM), which is part of the
Python runtime.
• If .pyc files are deleted, they will be regenerated when the script is run again.

2. File Handling

• Python uses open() to handle files.


• Modes:
o "r" → read, "w" → write, "a" → append, "rb"/"wb" → binary.
• Example:
• with open("data.txt", "w") as f:
• f.write("Hello AI")
3. Package vs Module

• Module: A single .py file containing functions, classes, variables.


• Package: A collection of modules organized in folders with __init__.py.
• Example:
o Module → math.py
o Package → numpy (contains many modules).

4. Decorators

• Functions that modify other functions without changing their code.


• Example:
• def log(func):
• def wrapper():
• print("Before call")
• func()
• return wrapper

• @log
• def greet():
• print("Hello")

5. Inheritance & Types

• Inheritance allows one class to derive from another.


• Types:
o Single: One base → one child
o Multiple: Child inherits from many classes
o Multilevel: Parent → Child → Grandchild
o Hierarchical: One parent, many children
o Hybrid: Combination
• Example:
• class Animal: pass
• class Dog(Animal): pass

6. Multithreading

• Allows multiple threads within a process.


• Useful for I/O-bound tasks (like network requests).
• Not true parallelism in Python because of the GIL (Global Interpreter Lock).
7. Why Python for AI

• Simple syntax, large libraries (NumPy, Pandas, scikit-learn, TensorFlow, PyTorch).


• Strong community support.
• Easy integration with other tools.

8. Lambda Functions

• Anonymous, one-line functions.


• Example:
• square = lambda x: x**2
• print(square(5)) # 25

9. Frameworks in Python

• For AI: TensorFlow, PyTorch, scikit-learn.


• For web: Django, Flask.
• For data: Pandas, NumPy.

10. Pass by Value vs Reference

• Python uses pass by object reference.


• Mutable objects (lists, dicts) → changes inside functions persist.
• Immutable (int, str, tuple) → no change.

11. Shallow Copy vs Deep Copy

• Shallow copy: Copies only references of nested objects.


• Deep copy: Copies everything recursively.
• Example:
• import copy
• a = [[1,2],[3,4]]
• b = copy.copy(a) # shallow
• c = copy.deepcopy(a) # deep

12. Overloading & Overriding


• Overloading: Same function name, different parameters (not natively supported,
simulated using *args).
• Overriding: Redefining parent method in child class.

13. Pandas Series vs DataFrame

• Series: 1D labeled array.


• DataFrame: 2D table with rows and columns.
• Example:
• import pandas as pd
• s = pd.Series([1,2,3])
• df = pd.DataFrame({"A":[1,2], "B":[3,4]})

14. Fibonacci & Prime Number Example

• Fibonacci:
• def fib(n):
• a,b=0,1
• for _ in range(n):
• print(a,end=" ")
• a,b = b,a+b
• Prime check:
• def is_prime(n):
• return all(n%i!=0 for i in range(2,int(n**0.5)+1))

15. Palindrome, Armstrong, Neon Number

• Palindrome: "121" same forward & backward.


• Armstrong: 153 → 1³+5³+3³=153.
• Neon: Square of number’s digits sum equals number (e.g., 9 → 9²=81 → 8+1=9).

16. Polymorphism

• Same interface, different implementations.


• Example:
• class Dog:
• def sound(self): print("Bark")
• class Cat:
• def sound(self): print("Meow")
17. Encapsulation

• Hiding implementation using private attributes (__var).


• Achieved with classes and access modifiers.

18. Methods & Types

• Instance methods → operate on object (self).


• Class methods → operate on class (@classmethod).
• Static methods → utility functions (@staticmethod).

19. Exception Handling

• Handle runtime errors with try-except-finally.


• Example:
• try: x=1/0
• except ZeroDivisionError: print("Can't divide by zero")

20. Getter & Setter

• Used to control attribute access.


• Example:
• class Student:
• def __init__(self,name): self.__name=name
• def get_name(self): return self.__name
• def set_name(self,n): self.__name=n

21. Super Keyword

• Used to call parent class methods.


• Example:
• class A:
• def show(self): print("A")
• class B(A):
• def show(self):
• super().show()
• print("B")

22. Neural Network (Basic)


• Composed of neurons (nodes), connected in layers:
o Input Layer → Hidden Layers → Output Layer.
• Each connection has weights and activation functions.

23. Broadcasting in AI (NumPy)

• NumPy automatically expands arrays of smaller shapes to match larger ones.


• Example:
• import numpy as np
• a = np.array([1,2,3])
• b = np.array([[1],[2]])
• print(a+b) # [[2,3,4],[3,4,5]]

24. Dunder Methods

• Special methods like __init__, __str__, __len__.


• Example:
• class Student:
• def __init__(self,name): self.name=name
• def __str__(self): return self.name

25. Multithreading vs Multiprocessing

• Multithreading: Multiple threads in one process (better for I/O-bound).


• Multiprocessing: Multiple processes (better for CPU-bound, true parallelism).

26. Activation Functions in AI

• Functions applied to neurons’ outputs.


• Types:
o Sigmoid: (0–1 range)
o ReLU: max(0, x)
o Tanh: (-1 to 1)
o Softmax: probabilities in classification.

27. List Comprehension

• Concise way to create lists.


• Example:
• [x**2 for x in range(5) if x%2==0] # [0,4,16]

28. is vs ==

• is: Checks identity (same object in memory).


• ==: Checks value equality.

29. args & kwargs

• *args: Variable length positional args.


• **kwargs: Variable length keyword args.
• Example:
• def demo(*args, **kwargs): print(args, kwargs)
• demo(1,2,a=3,b=4)

30. Confusion Matrix

• Table showing True Positives, True Negatives, False Positives, False Negatives.
• Helps evaluate classification models.

31. Closure

• Function that remembers variables from enclosing scope.


• Example:
• def outer(x):
• def inner(y): return x+y
• return inner
• add5 = outer(5)
• print(add5(3)) # 8

32. Monkey Patching

• Dynamically changing behavior of class/module at runtime.


• Example:
• class A: pass
• def new_method(self): print("Hi")
• A.say = new_method
• A().say()
Perfect then let’s stay with Python-only interview Q&A first. I’ll generate more questions
based on your syllabus + typical AI company Python interviews, and I’ll give detailed, well-
structured answers like the ones before.

Additional Python Interview Questions &


Answers

Q1. What are Python namespaces?

• Definition: A namespace is a mapping between names (identifiers) and objects in


Python.
• Types of namespaces:
1. Built-in namespace – preloaded functions (len, print).
2. Global namespace – variables declared at the top level of a script/module.
3. Local namespace – variables inside a function.
4. Enclosed (nonlocal) namespace – variables in nested functions.
• Example:
• x = 10 # global
• def func():
• y = 5 # local
• print(x + y)

Q2. Explain Python’s memory management.

• Python uses:
o Automatic garbage collection via reference counting + generational GC.
o Private heap space: all Python objects are stored here.
o Memory managers allocate/deallocate memory.
• Example of garbage collection:
• import gc
• gc.collect() # manually trigger garbage collection

Q3. What are Python’s data types?

• Numeric → int, float, complex


• Sequence → list, tuple, range
• Text → str
• Mapping → dict
• Set types → set, frozenset
• Boolean → bool
• NoneType → None

Q4. What is Python’s Global Interpreter Lock (GIL)?

• A mutex in CPython that prevents multiple native threads from executing Python
bytecode simultaneously.
• Ensures thread safety but limits parallelism in CPU-bound tasks.
• Solution: Use multiprocessing for CPU-bound tasks, threading for I/O-bound tasks.

Q5. What are Iterators and Generators?

• Iterator: An object implementing __iter__() & __next__() methods.


• Generator: Function that yields values using yield keyword, automatically creates an
iterator.
• Example:
• def gen():
• for i in range(3):
• yield i
• g = gen()
• print(next(g)) # 0

Q6. What are Python closures?

• Functions that capture variables from enclosing scope.


• Useful for decorators, callbacks.
• Example:
• def outer(x):
• def inner(y):
• return x + y
• return inner
• f = outer(10)
• print(f(5)) # 15

Q7. What are Python metaclasses?

• Definition: A class of a class.


• Used to control the creation of classes (like templates for classes).
• Example:
• class Meta(type):
• def __new__(cls, name, bases, dct):
• dct['hello'] = lambda self: "Hello"
• return super().__new__(cls, name, bases, dct)

• class MyClass(metaclass=Meta): pass
• print(MyClass().hello()) # Hello

Q8. What is the difference between @staticmethod, @classmethod, and instance


methods?

• Instance method: first argument is self. Works on object data.


• Class method: first argument is cls. Works on class-level data.
• Static method: No default argument. General utility.
• Example:
• class Demo:
• def instance_m(self): return "Instance"
• @classmethod
• def class_m(cls): return "Class"
• @staticmethod
• def static_m(): return "Static"

Q9. What is Python’s with statement?

• Simplifies resource management using context managers.


• Automatically handles setup and cleanup.
• Example:
• with open("file.txt", "w") as f:
• f.write("Hello")

Q10. Explain Python’s __slots__.

• Restricts attributes of a class to save memory.


• Example:
• class Person:
• __slots__ = ['name','age']
• def __init__(self,n,a): self.name=n; self.age=a

Q11. What is Monkey Patching?

• Changing a class or module at runtime.


• Example:
• class A: pass
• def new_func(self): return "Patched!"
• A.show = new_func
• print(A().show()) # Patched!

Q12. Explain difference between deep copy and shallow copy.

• Shallow copy: Copies references of nested objects.


• Deep copy: Copies objects recursively.
• Example:
• import copy
• a=[[1,2],[3,4]]
• b=copy.copy(a) # shallow
• c=copy.deepcopy(a) # deep

Q13. What are Python dunder methods?

• Double underscore methods that give special behavior.


• Examples:
o __init__ → constructor
o __str__ → string representation
o __len__ → length
o __add__ → operator overloading

Q14. Difference between Interpreter and Compiler?

• Interpreter: Executes code line by line (Python).


• Compiler: Translates entire code into machine code at once (C, Java).
• Python uses an interpreter + bytecode compiler (PVM).

Q15. What happens if .pyc files are deleted?

• Python regenerates them when the program is run again.


• .pyc files (in __pycache__) store compiled bytecode.

Q16. Explain Python’s *args and **kwargs.

• *args → variable-length positional arguments.


• **kwargs → variable-length keyword arguments.
• Example:
• def demo(*args, **kwargs):
• print(args, kwargs)
• demo(1,2, a=3,b=4)

Q17. What are Python exceptions?

• Runtime errors handled with try-except.


• Example:
• try:
• print(10/0)
• except ZeroDivisionError:
• print("Cannot divide by zero")

Q18. What is Polymorphism in Python?

• Same function name behaving differently depending on context.


• Example:
• print(len("abc")) # 3
• print(len([1,2,3])) # 3

Q19. What are Python design patterns commonly used?

• Singleton → only one instance.


• Factory → object creation control.
• Observer → event notification system.
• Decorator → dynamic behavior extension.

Q20. Explain Python’s memory optimization tools.

• __slots__ → restricts memory usage.


• del → deletes references.
• gc module → garbage collector.
• Generators instead of lists for large datasets.

You might also like