Skip to main content
Home  /  Knowledge Hub  /  Interview Questions

Interview Questions& Model Answers

Real questions. Real answers. Built from 20 years of actual hiring and being hired.

54
Total Questions
3
Technologies
3
Levels
✕ Clear filters

Showing 19 questions · Beginner

Clear all filters
PY-BEG-006 How does try-except-finally work in Python?
Python Core Python Beginner
3/10
Answer

'try' runs code that might fail. 'except' catches specific errors. 'finally' always runs regardless of whether an error occurred — used for cleanup.

Deep Explanation

The try block contains the risky code. If an exception occurs Python looks for a matching except clause. You can catch specific exception types (except ValueError) or use a bare except to catch everything (not recommended). The else clause (optional) runs only if no exception occurred. The finally clause always executes even if there was an exception or a return statement inside try — making it essential for releasing resources like file handles database connections or locks. Multiple except clauses can handle different exception types differently.

Real-World Example

In a database write operation: the try block executes the INSERT query the except block catches IntegrityError for duplicate keys and returns a meaningful error message the finally block always closes the database connection regardless of success or failure — preventing connection pool exhaustion.

⚠ Common Mistakes

Using a bare 'except:' that catches everything including KeyboardInterrupt and SystemExit making the program impossible to stop. Not closing resources in finally causing memory or connection leaks. Catching too broad an exception type and hiding real bugs.

🏭 Production Scenario

A production API server ran out of database connections after 6 hours because a developer forgot to close connections in a finally block. The try block opened a connection an exception occurred the connection was never closed and the pool was exhausted within hours under normal traffic.

Follow-up Questions
What is the difference between except Exception and bare except? When does finally NOT execute? How do context managers (with statement) relate to try-finally??
ID: PY-BEG-006  ·  Difficulty: 3/10  ·  Level: Beginner
PY-BEG-003 What are *args and **kwargs in Python functions?
Python Core Python Beginner
3/10
Answer

*args collects extra positional arguments as a tuple. **kwargs collects extra keyword arguments as a dictionary. Both allow functions to accept a variable number of arguments.

Deep Explanation

When you define a function with *args any positional arguments beyond the explicitly defined ones are packed into a tuple called args. With **kwargs any keyword arguments not explicitly defined are packed into a dictionary called kwargs. The names args and kwargs are just convention — the * and ** operators are what matter. You can use *args and **kwargs together and you can also use them when calling functions to unpack sequences and dictionaries into arguments. This pattern is heavily used in decorators, class inheritance, and API wrappers.

Real-World Example

Django's class-based views use **kwargs extensively to pass URL parameters captured by the router into view methods. FastAPI uses *args and **kwargs in middleware to forward requests without knowing the exact signature of the next handler.

⚠ Common Mistakes

Confusing *args (tuple) with a list. Forgetting that *args must come before **kwargs in the function signature. Trying to access args by keyword or kwargs by position. Mutating args thinking it is a list.

🏭 Production Scenario

A logging decorator in a production Flask app broke when a new endpoint added a keyword argument. The fix was changing the decorator to use *args and **kwargs so it would transparently forward any arguments to the wrapped function without needing updates every time a new parameter was added.

Follow-up Questions
How does ** unpacking work when calling a function? Can you have both *args and explicit keyword arguments? How are *args and **kwargs used in class __init__ with inheritance??
ID: PY-BEG-003  ·  Difficulty: 3/10  ·  Level: Beginner
PY-BEG-002 What does the ‘is’ operator do versus ‘==’?
Python Core Python Beginner
3/10
Answer

'==' checks value equality. 'is' checks identity — whether two variables point to the exact same object in memory.

Deep Explanation

The == operator calls the __eq__ method and compares values. The 'is' operator compares object identity using id(). Two objects can be equal in value but be different objects in memory. Python caches small integers (-5 to 256) and interned strings which can make 'is' return True unexpectedly for these values leading to subtle bugs if misused. You should almost never use 'is' to compare values — reserve it for None checks (if x is None) where it is both correct and idiomatic.

Real-World Example

In a user authentication system: 'if user_role == admin_role' correctly compares role names as strings. Using 'is' instead works on small test data due to string interning but silently fails in production when role strings come from a database and are different objects with the same value.

⚠ Common Mistakes

Using 'is' to compare strings or integers expecting value equality. Being confused by small integer caching making 'is' appear to work correctly during testing. Not using 'is None' — using == None instead which is slower and less Pythonic.

🏭 Production Scenario

A production bug was caused by comparing user permission strings with 'is' instead of '=='. Tests passed because short strings were interned but in production with database-fetched strings the comparison always returned False locking all users out of admin features.

Follow-up Questions
What is object identity in Python? How does Python intern strings? Why is 'is None' preferred over '== None'??
ID: PY-BEG-002  ·  Difficulty: 3/10  ·  Level: Beginner
ML-BEG-006 What is cross-validation and why is it better than a single train-test split?
Machine Learning AI/ML Beginner
4/10
Answer

Cross-validation trains and evaluates a model multiple times on different subsets of data giving a more reliable estimate of generalization performance especially for small datasets. The most common form is k-fold cross-validation.

Deep Explanation

In k-fold cross-validation the dataset is split into k equal parts (folds). The model is trained k times each time using k-1 folds for training and 1 fold for validation. The final performance metric is the average across all k evaluations and you also get a standard deviation showing how stable the model is. Common choices: k=5 (20% validation each time) or k=10 (10% validation). Benefits over single split: uses all data for both training and validation (important for small datasets) provides confidence intervals on performance (single split gives one number — is it lucky or representative?) and reveals if the model is sensitive to which data is in training vs validation (high variance = potential overfitting). Stratified k-fold maintains class proportions in each fold — essential for imbalanced classification.

Real-World Example

A medical ML model for rare disease diagnosis had only 800 labeled examples. A single 80/20 split would train on 640 examples and validate on 160 — too few for either. 10-fold cross-validation trained 10 models each on 720 examples and validated on 80 giving a reliable performance estimate with confidence intervals and using all data for both training and evaluation.

⚠ Common Mistakes

Using k-fold cross-validation for hyperparameter tuning and reporting those scores as test performance (data leakage — use nested cross-validation instead). Not using stratified folds for imbalanced classification. Ignoring the standard deviation across folds — high variance means the model is sensitive to data splits which is itself a problem. Applying cross-validation to time-series data without using TimeSeriesSplit.

🏭 Production Scenario

A production model selection process used 5-fold cross-validation to compare 20 candidate models. The winning model had a mean AUC of 0.87 with standard deviation 0.02 — indicating stable performance across folds. The runner-up had mean AUC 0.86 with standard deviation 0.09 — highly variable and less trustworthy. The stable model was selected and performed as expected in production.

Follow-up Questions
What is nested cross-validation and when do you need it? What is TimeSeriesSplit and why can't you use standard k-fold for time-series? What is sklearn Pipeline and why does it matter for cross-validation??
ID: ML-BEG-006  ·  Difficulty: 4/10  ·  Level: Beginner

PAGE 2 OF 2  ·  19 QUESTIONS TOTAL