🐍 Advanced Python Quiz
Challenge yourself with interview-level Python questions designed for developers
60
Questions4
Levels100%
Free
Question:
1/60
Score:
0
Time:
00:00
Medium
1. What is the output?
def func(a=[]):
a.append(1)
return a
print(func())
print(func())
[1] [1]
[1] [1,1]
Error
None
Hard
2. Which Python feature enables lazy evaluation?
Lists
Generators
Tuples
Sets
Hard
3. Which statement about the GIL is correct?
Threads always execute simultaneously.
Only one thread executes Python bytecode at a time.
The GIL affects multiprocessing only.
The GIL speeds up CPU-bound threading.
Expert
4. Which special method makes an object callable?
__init__
__call__
__new__
__repr__
Expert
5. Which module provides the lru_cache decorator?
collections
functools
typing
itertools
Hard
6. What is the output?
x = (i*i for i in range(3)) print(next(x)) print(next(x))
1 4
0 1
0 4
Error
Expert
7. Which module is primarily used for asynchronous programming?
threading
multiprocessing
asyncio
queue
Expert
8. Which decorator converts an instance method into a class method?
@property
@staticmethod
@classmethod
@abstractmethod
Expert
10. Which statement about decorators is TRUE?
Decorators can only modify classes.
Decorators always return None.
Decorators wrap another callable to extend behavior.
Decorators are only available from Python 3.10.
Correct Answer:
Decorators wrap another callable.
A decorator takes a function (or class), adds behavior, and returns a new callable while preserving the original interface.
A decorator takes a function (or class), adds behavior, and returns a new callable while preserving the original interface.
Expert
11. What will happen when using __slots__ in a Python class?
It automatically creates database tables.
It reduces memory usage by preventing a normal instance dictionary.
It makes the class immutable.
It disables inheritance completely.
Correct Answer:
It reduces memory usage.
Normally Python objects store attributes inside
Interview Tip: __slots__ is commonly asked in performance-focused Python interviews.
Normally Python objects store attributes inside
__dict__.
Using __slots__ creates a fixed attribute layout and can significantly reduce memory consumption when creating many objects.
Interview Tip: __slots__ is commonly asked in performance-focused Python interviews.
Expert
12. What is the Method Resolution Order (MRO) used for?
Improving Python execution speed.
Determining the order in which classes are searched during inheritance.
Creating database relationships.
Managing memory allocation.
Correct Answer:
Determining class search order.
Python uses C3 linearization to calculate MRO. You can inspect it using:
Interview Tip: MRO questions are common when discussing multiple inheritance and the diamond problem.
Python uses C3 linearization to calculate MRO. You can inspect it using:
ClassName.mro()
Interview Tip: MRO questions are common when discussing multiple inheritance and the diamond problem.
Expert
13. What is the output of this code?
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@decorator
def hello():
print("Hello")
hello()
Hello Before After
Before Hello After
Before After Hello
Error
Correct Answer:
Before Hello After
A decorator replaces the original function with the wrapper function. The wrapper controls when the original function executes.
Interview Tip: Decorators are heavily used in frameworks like Flask, Django, and FastAPI for authentication, routing, and middleware.
A decorator replaces the original function with the wrapper function. The wrapper controls when the original function executes.
Interview Tip: Decorators are heavily used in frameworks like Flask, Django, and FastAPI for authentication, routing, and middleware.
Hard
14. What does this function return?
def outer(x):
def inner():
return x + 10
return inner
func = outer(5)
print(func())
10
15
Error because x is deleted
None
Correct Answer:
15
The inner function remembers variables from the enclosing scope. This behavior is called a closure.
Even after
Interview Tip: Closures are commonly used for decorators, factories, and maintaining state without classes.
The inner function remembers variables from the enclosing scope. This behavior is called a closure.
Even after
outer() finishes execution, the value of x is preserved.
Interview Tip: Closures are commonly used for decorators, factories, and maintaining state without classes.
Expert
15. Which methods are required to create a custom context manager class?
__init__ and __del__
__enter__ and __exit__
__start__ and __stop__
open() and close()
Correct Answer:
__enter__ and __exit__
Context managers control resource handling using the
The context manager automatically releases resources after the block completes.
Interview Tip: Database connections, locks, and file handling commonly use context managers.
Context managers control resource handling using the
with statement.
Example:
with open("file.txt") as f:
data=f.read()
The context manager automatically releases resources after the block completes.
Interview Tip: Database connections, locks, and file handling commonly use context managers.
Hard
16. What is the main advantage of using generators instead of lists?
Generators execute faster in every situation.
Generators produce values lazily and save memory.
Generators allow random indexing.
Generators store all values permanently.
Correct Answer:
Generators produce values lazily and save memory.
A list stores all elements in memory:
Interview Tip: Generators are preferred when processing large datasets, files, streams, or infinite sequences.
A list stores all elements in memory:
numbers=[x*x for x in range(1000000)]A generator produces values only when requested:
numbers=(x*x for x in range(1000000))
Interview Tip: Generators are preferred when processing large datasets, files, streams, or infinite sequences.
Expert
17. What happens when a Python function contains the yield keyword?
It becomes a normal function.
It becomes a generator function.
It automatically runs asynchronously.
It creates a new thread.
Correct Answer:
It becomes a generator function.
When Python sees
The function pauses at each yield and resumes later.
Interview Tip: Understanding yield is important for memory-efficient Python programming.
When Python sees
yield, it creates a generator object instead of executing the function immediately.
Example:
def count():
yield 1
yield 2
yield 3
for x in count():
print(x)
The function pauses at each yield and resumes later.
Interview Tip: Understanding yield is important for memory-efficient Python programming.
Expert
18. What does functools.partial() do?
It converts a function into a generator.
It creates a new function with some arguments already filled.
It deletes unused function parameters.
It improves CPU performance automatically.
Correct Answer:
It creates a new function with predefined arguments.
Example:
Interview Tip: partial() is useful for creating specialized versions of existing functions.
from functools import partial
def multiply(a,b):
return a*b
double = partial(multiply,2)
print(double(5))
Output:
10
Interview Tip: partial() is useful for creating specialized versions of existing functions.
Expert
19. What is a metaclass in Python?
A class that can only create objects.
A class that defines how classes are created.
A replacement for inheritance.
A faster version of normal classes.
Correct Answer:
A class that defines how classes are created.
In Python, classes are objects too. A metaclass controls the creation and behavior of classes. Example:
The default metaclass in Python is
Interview Tip: Metaclasses are rarely needed in daily development but are important for understanding frameworks like Django ORM.
In Python, classes are objects too. A metaclass controls the creation and behavior of classes. Example:
class Meta(type):
pass
class MyClass(
metaclass=Meta
):
pass
The default metaclass in Python is
type.
Interview Tip: Metaclasses are rarely needed in daily development but are important for understanding frameworks like Django ORM.
Expert
20. Which special methods make an object a descriptor?
__init__ and __del__
__get__, __set__, and __delete__
__call__ and __repr__
__enter__ and __exit__
Correct Answer:
__get__, __set__, and __delete__
Descriptors customize attribute access behavior. Example:
Python properties, methods, and many framework features internally use descriptors.
Interview Tip: Understanding descriptors helps explain how
Descriptors customize attribute access behavior. Example:
class Descriptor:
def __get__(
self,
obj,
owner
):
return "value"
Python properties, methods, and many framework features internally use descriptors.
Interview Tip: Understanding descriptors helps explain how
@property works internally.
Hard
21. Which module provides Abstract Base Classes in Python?
abstract
abc
interface
oop
Correct Answer:
abc
Python provides abstract classes using the
A subclass must implement the abstract method before it can be instantiated.
Interview Tip: Abstract classes are useful when designing large systems where certain behaviors must be enforced.
Python provides abstract classes using the
abc module.
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
A subclass must implement the abstract method before it can be instantiated.
Interview Tip: Abstract classes are useful when designing large systems where certain behaviors must be enforced.
Expert
22. What problem does Python's MRO help solve?
Memory allocation problems.
Ambiguity in multiple inheritance.
Database connection issues.
Thread synchronization.
Correct Answer:
Ambiguity in multiple inheritance.
The Diamond Problem occurs when multiple parent classes inherit from the same base class. Example:
Interview Tip: MRO questions are common for senior Python developer interviews.
The Diamond Problem occurs when multiple parent classes inherit from the same base class. Example:
A
/ \
B C
\ /
D
Python uses C3 Linearization to determine the correct method lookup order.
You can inspect it using:
D.mro()
Interview Tip: MRO questions are common for senior Python developer interviews.
Hard
23. What is the purpose of super() in Python?
It creates a new object.
It allows access to methods from a parent class according to MRO.
It bypasses inheritance.
It converts a class into an abstract class.
Correct Answer:
It accesses parent class methods according to MRO.
Example:
Using
Interview Tip: Always prefer
class Parent:
def show(self):
print("Parent")
class Child(Parent):
def show(self):
super().show()
print("Child")
Using
super() is safer than directly calling the parent class because it respects Python's MRO.
Interview Tip: Always prefer
super() in cooperative multiple inheritance.
Hard
24. What is the main advantage of using @dataclass?
It converts Python into a compiled language.
It automatically generates common class methods like __init__ and __repr__.
It removes the need for inheritance.
It creates database models automatically.
Correct Answer:
It generates common methods automatically.
Example:
Interview Tip: Dataclasses are preferred for storing structured data without writing repetitive boilerplate code.
from dataclasses import dataclass
@dataclass
class User:
name:str
age:int
Python automatically creates:
- __init__()
- __repr__()
- __eq__()
Interview Tip: Dataclasses are preferred for storing structured data without writing repetitive boilerplate code.
Expert
25. How does CPython primarily manage memory?
Only through manual memory allocation.
Reference counting combined with garbage collection.
Only through the operating system.
By deleting unused variables immediately.
Correct Answer:
Reference counting combined with garbage collection.
CPython keeps track of how many references point to an object. Example:
However, reference counting alone cannot handle circular references, so Python also has a cyclic garbage collector.
Interview Tip: Understanding memory management helps when optimizing large Python applications.
CPython keeps track of how many references point to an object. Example:
a = [1,2,3] b = aThe list now has two references. When the reference count reaches zero, CPython can release the memory.
However, reference counting alone cannot handle circular references, so Python also has a cyclic garbage collector.
Interview Tip: Understanding memory management helps when optimizing large Python applications.
Hard
26. Why does Python need a garbage collector if it already uses reference counting?
Reference counting is too slow for integers.
Garbage collection handles circular references.
Garbage collection replaces variables.
It improves syntax checking.
Correct Answer:
Garbage collection handles circular references.
Example:
Interview Tip: Circular references are a common topic when discussing memory leaks.
Example:
a = [] b = [] a.append(b) b.append(a)Here, objects reference each other. Their reference counts never reach zero, even though they are no longer needed. The garbage collector detects and removes such unreachable cycles.
Interview Tip: Circular references are a common topic when discussing memory leaks.
Hard
27. Which statement about mutable and immutable objects is correct?
Lists are immutable.
Lists are mutable, while tuples are immutable.
Strings can be modified in place.
Integers are mutable.
Correct Answer:
Lists are mutable, tuples are immutable.
Mutable objects can change their contents without creating a new object. Example:
Interview Tip: Mutable default arguments are a very common Python interview trap.
Mutable objects can change their contents without creating a new object. Example:
items=[1,2] items.append(3)The same list object is modified. Immutable objects create a new object when changed. Example:
name="Python" name+="3"A new string object is created.
Interview Tip: Mutable default arguments are a very common Python interview trap.
Expert
28. What is the difference between copy.copy() and copy.deepcopy()?
copy.copy() creates a completely independent copy of nested objects.
copy.copy() creates a shallow copy while copy.deepcopy() recursively copies nested objects.
Both methods behave exactly the same.
deepcopy() only works with dictionaries.
Correct Answer:
copy.copy() creates a shallow copy while deepcopy() recursively copies nested objects.
Example:
Interview Tip: This is a common question when discussing bugs caused by shared mutable data.
Example:
import copy original = [[1,2],[3,4]] shallow = copy.copy(original) deep = copy.deepcopy(original)A shallow copy creates a new outer object but keeps references to nested objects. A deep copy creates completely independent nested objects.
Interview Tip: This is a common question when discussing bugs caused by shared mutable data.
Hard
29. What is the purpose of weak references in Python?
They make objects execute faster.
They reference objects without preventing garbage collection.
They duplicate objects automatically.
They replace normal variables.
Correct Answer:
They reference objects without preventing garbage collection.
Normal references increase an object's reference count. Weak references do not keep the object alive. Example:
Interview Tip: Weak references are useful in caches where you don't want stored objects to consume memory forever.
Normal references increase an object's reference count. Weak references do not keep the object alive. Example:
import weakref
class User:
pass
user = User()
ref = weakref.ref(user)
Interview Tip: Weak references are useful in caches where you don't want stored objects to consume memory forever.
Expert
30. Why can __slots__ improve performance?
It converts Python code into machine code.
It reduces memory usage by avoiding instance dictionaries.
It removes the need for objects.
It disables all attributes.
Correct Answer:
It reduces memory usage by avoiding instance dictionaries.
Normally:
Interview Tip: Useful when creating thousands or millions of lightweight objects.
Normally:
class User:
pass
creates objects with a dynamic:
__dict__Using:
class User:
__slots__ = ["name"]
creates a fixed memory layout.
Interview Tip: Useful when creating thousands or millions of lightweight objects.
Hard
31. Which Python object type is immutable?
List
Dictionary
Tuple
Set
Correct Answer:
Tuple
Immutable objects cannot be modified after creation. Examples:
Interview Tip: Immutable objects are hashable and can often be used as dictionary keys.
Immutable objects cannot be modified after creation. Examples:
- int
- float
- str
- tuple
- frozenset
- list
- dict
- set
Interview Tip: Immutable objects are hashable and can often be used as dictionary keys.
Expert
32. What happens when you use a mutable default argument?
Python creates a new object every function call.
The same object is reused between function calls.
Python throws a syntax error.
The argument becomes immutable.
Correct Answer:
The same object is reused between function calls.
Example:
Interview Tip: This is one of the most frequently asked Python interview questions.
Example:
def add(item, data=[]):
data.append(item)
return data
The list is created once when the function is defined, not every time it is called.
Better approach:
def add(item, data=None):
if data is None:
data=[]
Interview Tip: This is one of the most frequently asked Python interview questions.
Expert
33. What is the main purpose of asyncio in Python?
To execute Python code faster using compilation.
To handle many asynchronous I/O operations efficiently.
To replace all multiprocessing use cases.
To remove the Global Interpreter Lock.
Correct Answer:
To handle many asynchronous I/O operations efficiently.
The
Async programming is especially useful for:
Interview Tip: asyncio improves concurrency, not raw CPU performance.
The
asyncio module provides:
- Event loop
- Coroutines
- Tasks
- Futures
import asyncio
async def hello():
print("Hello")
asyncio.run(hello())
Async programming is especially useful for:
- API calls
- Web servers
- Network operations
- Database queries
Interview Tip: asyncio improves concurrency, not raw CPU performance.
Expert
34. What is an event loop in asyncio?
A loop that repeats Python code forever.
A mechanism that schedules and executes asynchronous tasks.
A replacement for Python loops.
A memory management system.
Correct Answer:
A mechanism that schedules and executes asynchronous tasks.
The event loop continuously checks:
Interview Tip: Understanding the event loop is essential for FastAPI and high-performance Python services.
The event loop continuously checks:
- Which tasks are ready
- Which operations completed
- Which coroutine should continue
async def download():
await fetch_data()
The event loop pauses the coroutine while waiting and runs other tasks.
Interview Tip: Understanding the event loop is essential for FastAPI and high-performance Python services.
Hard
35. What is the difference between threading and multiprocessing?
They are exactly the same.
Threading uses threads in one process, while multiprocessing creates separate processes.
Multiprocessing cannot run Python code.
Threading always uses multiple CPU cores.
Correct Answer:
Threading uses threads in one process, multiprocessing creates separate processes.
Threading:
Multiprocessing:
Interview Tip: Choose threading for I/O-bound work and multiprocessing for CPU-bound work.
Threading:
Thread | ProcessShares memory and is useful for I/O tasks.
Multiprocessing:
Process 1 Process 2 Process 3Uses separate memory spaces and can use multiple CPU cores.
Interview Tip: Choose threading for I/O-bound work and multiprocessing for CPU-bound work.
Expert
36. What problem does Python's GIL create?
It prevents Python from creating variables.
It prevents multiple threads from executing Python bytecode simultaneously.
It disables asynchronous programming.
It removes garbage collection.
Correct Answer:
It prevents multiple threads from executing Python bytecode simultaneously.
The Global Interpreter Lock (GIL) allows only one thread at a time to execute Python bytecode in CPython.
Example:
However, threads can still be useful for I/O operations because waiting happens outside Python execution.
Interview Tip: GIL mainly affects CPU-bound multithreading.
The Global Interpreter Lock (GIL) allows only one thread at a time to execute Python bytecode in CPython.
Example:
Thread A | Python Bytecode Thread B | Waiting
However, threads can still be useful for I/O operations because waiting happens outside Python execution.
Interview Tip: GIL mainly affects CPU-bound multithreading.
Expert
37. Which approach is better for CPU-intensive calculations?
Asyncio
Threading
Multiprocessing
Generators
Correct Answer:
Multiprocessing
CPU-heavy examples:
Interview Tip: A common interview question: "Threading or multiprocessing?" Answer: I/O-bound → Threading / Asyncio CPU-bound → Multiprocessing
CPU-heavy examples:
- Image processing
- Machine learning calculations
- Large mathematical operations
- Data transformation
from multiprocessing import Process
p = Process(
target=work
)
p.start()
Interview Tip: A common interview question: "Threading or multiprocessing?" Answer: I/O-bound → Threading / Asyncio CPU-bound → Multiprocessing
Hard
38. What is the main purpose of type hints in Python?
They convert Python into a statically typed language.
They provide optional type information for better readability and tooling.
They improve Python execution speed automatically.
They prevent all runtime errors.
Correct Answer:
They provide optional type information for better readability and tooling.
Example:
Interview Tip: Type hints improve maintainability in large Python projects.
Example:
def add(
a:int,
b:int
) -> int:
return a+b
Python does not enforce these types during normal execution.
Tools like:
- MyPy
- Pyright
- IDE analyzers
Interview Tip: Type hints improve maintainability in large Python projects.
Expert
39. What problem do Generic types solve in Python typing?
They execute code faster.
They allow reusable type-safe code for different data types.
They replace inheritance.
They remove the need for classes.
Correct Answer:
They allow reusable type-safe code for different data types.
Example:
Interview Tip: Generics are common in libraries and large enterprise codebases.
Example:
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self,value:T):
self.value=value
The same class can work with:
Box[int] Box[str]
Interview Tip: Generics are common in libraries and large enterprise codebases.
Expert
40. What is the purpose of typing.Protocol?
It creates database protocols.
It enables structural typing based on behavior.
It forces class inheritance.
It replaces abstract classes completely.
Correct Answer:
It enables structural typing based on behavior.
Traditional inheritance:
Interview Tip: Protocols support cleaner dependency design and are inspired by "duck typing".
Traditional inheritance:
class Dog(Animal)Protocol checks whether an object has the required methods. Example:
from typing import Protocol
class Speaker(Protocol):
def speak(self):
...
Any object with a compatible speak() method satisfies the protocol.
Interview Tip: Protocols support cleaner dependency design and are inspired by "duck typing".
Hard
41. What is TypedDict used for?
Creating database tables.
Providing type information for dictionaries with fixed keys.
Replacing normal dictionaries.
Creating immutable dictionaries.
Correct Answer:
Providing type information for dictionaries with fixed keys.
Example:
Interview Tip: TypedDict is useful when working with JSON responses and API data.
Example:
from typing import TypedDict
class User(TypedDict):
name:str
age:int
Usage:
user = {
"name":"John",
"age":30
}
Interview Tip: TypedDict is useful when working with JSON responses and API data.
Expert
42. What feature was introduced by match-case syntax in Python 3.10?
Multiple inheritance.
Structural pattern matching.
Automatic compilation.
New garbage collection.
Correct Answer:
Structural pattern matching.
Example:
Interview Tip: Python pattern matching is useful for parsing complex data structures.
Example:
command="start"
match command:
case "start":
print("Running")
case "stop":
print("Stopped")
Pattern matching is more powerful than a simple if/elif chain.
Interview Tip: Python pattern matching is useful for parsing complex data structures.
Hard
43. What is the difference between "raise" and "raise from" in Python?
They are exactly the same.
raise from preserves the original exception context.
raise from improves execution speed.
raise disables exceptions.
Correct Answer:
raise from preserves the original exception context.
Example:
This makes debugging production issues much easier.
Interview Tip: Senior developers should understand exception chaining.
Example:
try:
value = int("abc")
except ValueError as e:
raise RuntimeError(
"Conversion failed"
) from e
The original error is attached to the new exception.
This makes debugging production issues much easier.
Interview Tip: Senior developers should understand exception chaining.
Hard
44. What is the recommended way to create custom exceptions?
Modify built-in Python exceptions.
Create a class inheriting from Exception.
Create a global variable.
Use print statements.
Correct Answer:
Create a class inheriting from Exception.
Example:
Interview Tip: Large applications usually define domain-specific exceptions.
class PaymentError(Exception):
pass
raise PaymentError(
"Payment failed"
)
Custom exceptions make application errors clearer and easier to handle.
Interview Tip: Large applications usually define domain-specific exceptions.
Expert
45. What problem does ExceptionGroup solve in Python 3.11?
It replaces all exceptions.
It allows handling multiple exceptions together.
It improves CPU performance.
It removes try-except blocks.
Correct Answer:
It allows handling multiple exceptions together.
Example:
This is useful in concurrent applications where multiple tasks may fail independently.
Interview Tip: Exception Groups are important when working with asyncio task groups.
raise ExceptionGroup(
"Errors",
[
ValueError(),
TypeError()
]
)
Handling:
except* ValueError:
pass
This is useful in concurrent applications where multiple tasks may fail independently.
Interview Tip: Exception Groups are important when working with asyncio task groups.
Hard
46. Which module is recommended for modern filesystem operations?
os.path only
pathlib
filesystem
filemanager
Correct Answer:
pathlib
Example:
Interview Tip: Modern Python projects prefer pathlib over manual string path manipulation.
Example:
from pathlib import Path
file = Path(
"data.txt"
)
print(file.exists())
Advantages:
- Object-oriented API
- Cleaner path handling
- Cross-platform support
Interview Tip: Modern Python projects prefer pathlib over manual string path manipulation.
Expert
47. What is a major difference between JSON and Pickle?
JSON is always faster.
JSON is language-independent, while Pickle is Python-specific.
Pickle creates HTML files.
JSON can serialize every Python object.
Correct Answer:
JSON is language-independent, while Pickle is Python-specific.
JSON example:
Interview Tip: Never unpickle data received from unknown sources.
JSON example:
{
"name":"Python",
"version":3
}
JSON supports:
- Strings
- Numbers
- Lists
- Dictionaries
Interview Tip: Never unpickle data received from unknown sources.
Hard
48. Why are context managers useful when working with database connections?
They make SQL queries faster automatically.
They ensure resources are properly acquired and released.
They replace databases.
They remove the need for transactions.
Correct Answer:
They ensure resources are properly acquired and released.
Example:
Interview Tip: Resource management is critical in production applications.
Example:
with database.connect() as conn:
result = conn.execute(query)
The context manager can automatically:
- Open connections
- Commit transactions
- Rollback failures
- Close resources
Interview Tip: Resource management is critical in production applications.
Expert
49. What does functools.lru_cache provide?
Automatic parallel execution.
A Least Recently Used cache for function results.
Database caching.
Memory cleanup.
Correct Answer:
A Least Recently Used cache for function results.
Example:
Interview Tip: Caching is useful when a function is expensive but receives repeated inputs.
Example:
from functools import lru_cache
@lru_cache(maxsize=100)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1)+fibonacci(n-2)
The function result is stored and reused for repeated inputs.
Interview Tip: Caching is useful when a function is expensive but receives repeated inputs.
Expert
50. What is memoization?
Deleting unused variables.
Storing previous computation results to avoid repeated work.
Converting Python code to C.
Creating multiple threads.
Correct Answer:
Storing previous computation results.
Example: Without memoization:
Interview Tip: Dynamic programming solutions often use memoization.
Example: Without memoization:
fib(40)may repeat many calculations. With memoization:
fib(40)is calculated once and reused.
Interview Tip: Dynamic programming solutions often use memoization.
Hard
51. Which tool is commonly used for profiling Python performance?
pip
cProfile
venv
pytest
Correct Answer:
cProfile
Example:
Interview Tip: Always measure before optimizing. Performance assumptions are often wrong.
Example:
python -m cProfile app.pyIt measures:
- Function execution time
- Number of calls
- Performance bottlenecks
Interview Tip: Always measure before optimizing. Performance assumptions are often wrong.
Expert
52. Which approach usually improves Python application performance?
Adding more print statements.
Reducing unnecessary work and optimizing bottlenecks.
Making every function asynchronous.
Using global variables everywhere.
Correct Answer:
Reducing unnecessary work and optimizing bottlenecks.
Common optimization techniques:
Interview Tip: Senior engineers optimize based on measurements, not assumptions.
Common optimization techniques:
- Use appropriate data structures
- Cache expensive operations
- Avoid unnecessary loops
- Use generators for large data
- Profile before changing code
Interview Tip: Senior engineers optimize based on measurements, not assumptions.
Hard
53. What is the main purpose of unit testing?
To make code execute faster.
To verify individual components work correctly.
To replace debugging completely.
To automatically deploy applications.
Correct Answer:
To verify individual components work correctly.
A unit test checks a small isolated piece of code. Example:
Benefits:
Interview Tip: Good developers write tests around behavior, not implementation details.
A unit test checks a small isolated piece of code. Example:
def add(a,b):
return a+b
def test_add():
assert add(2,3)==5
Benefits:
- Find bugs early
- Enable safer refactoring
- Improve code confidence
Interview Tip: Good developers write tests around behavior, not implementation details.
Expert
54. What is the purpose of mocking in Python tests?
To permanently replace functions.
To simulate external dependencies during testing.
To increase production performance.
To remove the need for tests.
Correct Answer:
To simulate external dependencies during testing.
Example: Instead of calling a real API:
Useful for:
Interview Tip: Mocking makes tests faster and more reliable.
Example: Instead of calling a real API:
response = api.get_user()A test can use a mock:
mock_api.get_user.return_value = user
Useful for:
- APIs
- Databases
- External services
Interview Tip: Mocking makes tests faster and more reliable.
Expert
55. What is dependency injection?
Creating dependencies inside every function.
Providing dependencies from outside instead of creating them internally.
Removing all dependencies.
Installing Python packages automatically.
Correct Answer:
Providing dependencies from outside.
Without dependency injection:
Advantages:
Interview Tip: Dependency injection is common in enterprise applications.
Without dependency injection:
class Service:
def __init__(self):
self.db = Database()
With dependency injection:
class Service:
def __init__(self,db):
self.db=db
Advantages:
- Easier testing
- Better flexibility
- Looser coupling
Interview Tip: Dependency injection is common in enterprise applications.
Hard
56. Why is logging preferred over print statements in production?
Logging always runs faster.
Logging provides levels, formatting, and output control.
Print statements cannot display text.
Logging removes all bugs.
Correct Answer:
Logging provides levels, formatting, and output control.
Python logging supports:
Interview Tip: Production systems need searchable and structured logs.
Python logging supports:
- DEBUG
- INFO
- WARNING
- ERROR
- CRITICAL
import logging
logging.error(
"Database failed"
)
Interview Tip: Production systems need searchable and structured logs.
Expert
57. What is the best first step when debugging a production issue?
Immediately rewrite the code.
Collect information using logs, metrics, and error traces.
Restart everything without investigation.
Disable monitoring.
Correct Answer:
Collect information using logs, metrics, and error traces.
A production debugging workflow:
Interview Tip: Senior engineers debug systematically instead of guessing.
A production debugging workflow:
- Check error logs
- Identify affected systems
- Reproduce if possible
- Find root cause
- Apply and test the fix
Interview Tip: Senior engineers debug systematically instead of guessing.
Expert
58. Which design principle encourages a class to have only one reason to change?
DRY Principle
Single Responsibility Principle
Open/Closed Principle
Dependency Inversion Principle
Correct Answer:
Single Responsibility Principle.
The Single Responsibility Principle (SRP) states that a class should focus on one responsibility. Bad design:
Interview Tip: Senior Python developers are expected to design maintainable systems, not just write working code.
The Single Responsibility Principle (SRP) states that a class should focus on one responsibility. Bad design:
class User:
save_database()
send_email()
generate_report()
Better:
UserRepository EmailService ReportService
Interview Tip: Senior Python developers are expected to design maintainable systems, not just write working code.
Expert
59. What does the Open/Closed Principle mean?
All code should be placed in one file.
Software should be open for extension but closed for modification.
Classes should never use inheritance.
Functions should never change.
Correct Answer:
Open for extension but closed for modification.
Example: Instead of modifying existing payment code:
Interview Tip: This principle reduces bugs when applications grow.
Example: Instead of modifying existing payment code:
if payment=="card":
process_card()
elif payment=="paypal":
process_paypal()
Create extensible classes:
class PaymentProcessor:
def pay(self):
pass
New payment types can be added without changing old code.
Interview Tip: This principle reduces bugs when applications grow.
Expert
60. What separates a senior Python developer from a beginner developer?
Knowing more Python keywords.
Writing the longest code possible.
Designing reliable, maintainable, and scalable solutions.
Avoiding all third-party libraries.
Correct Answer:
Designing reliable, maintainable, and scalable solutions.
Senior Python development includes:
Interview Tip: Companies evaluate experienced developers on problem solving and design thinking, not only syntax knowledge.
Senior Python development includes:
- Writing clean architecture
- Understanding performance trade-offs
- Testing properly
- Debugging production systems
- Making good engineering decisions
Interview Tip: Companies evaluate experienced developers on problem solving and design thinking, not only syntax knowledge.
🎉 Quiz Completed
0%
Keep practicing advanced Python concepts.
Real expertise comes from writing and reviewing production code.
Comments
Post a Comment