Python for AI viva and interview questions (101 with answers)
The questions examiners and interviewers ask most, unit by unit, with short answers you can say out loud. ⭐ marks the ones asked most often. Practise them as flash cards in the garage (🎤 Viva practice).
▶ Practise with flash cardsUnit 1: Fundamentals & control flow
⭐ What kind of language is Python?
High-level, interpreted (compiled to bytecode and run by the PVM), dynamically typed, strongly typed, multi-paradigm (procedural, OOP, functional). Created by Guido van Rossum, released 1991.
Application areas?
AI/ML, data science, web (Django/Flask), automation/scripting, scientific computing, testing, desktop apps, games, IoT, cybersecurity.
Jupyter vs VS Code?
Jupyter runs code in cells, keeps state between them, and mixes code, output, plots and markdown, so it suits exploration. VS Code is an editor/IDE for .py files, with debugging, extensions and git, so it suits projects. VS Code can also open .ipynb files.
⭐ Identifier rules?
Letters, digits and _; can't start with a digit; case-sensitive; can't be a keyword; no spaces or symbols.
What is a keyword? Examples?
A reserved word with fixed meaning: if, for, while, def, return, class, import, True, None, and, or, not, lambda, try, with. import keyword; keyword.kwlist.
Statement vs expression?
An expression produces a value (2 + 3). A statement performs an action (x = 5, if, for). Every expression can be a statement, but not the other way round.
⭐ Basic data types?
int, float, complex, str, bool, NoneType. Collections: list, tuple, set, dict.
⭐ Mutable vs immutable?
Mutable (can change in place): list, dict, set. Immutable: int, float, str, tuple, bool, frozenset.
⭐ Type casting: implicit vs explicit?
Implicit: Python converts automatically (3 + 2.5 → 5.5). Explicit: you convert (int("5"), str(9), float("2.5")). int("3.5") raises ValueError.
⭐ / vs // vs %?
/ true division (always float), // floor division (rounds toward −∞, so -7//2 = -4), % remainder (takes the sign of the divisor, so -7%3 = 2).
⭐ == vs is?
== compares values; is checks whether two names point to the same object (identity). Use is only for None.
⭐ Operator precedence order?
() → → unary +x -x ~x → * / // % → + - → shifts → & → ^ → | → comparisons → not → and → or. is right-associative: 232 = 512.
Logical operators & short-circuit?
and, or, not. and stops at the first falsy value, or stops at the first truthy one, so 0 or "x" gives "x".
⭐ Are strings mutable?
No. s[0] = "a" → TypeError. Methods return new strings.
⭐ Slicing s[start:stop:step]?
Stop is excluded. s[::-1] reverses. s[-1] is the last char. Out-of-range slices don't raise errors.
Common string methods?
upper lower strip split join replace find index count startswith endswith isdigit isalpha isalnum title format.
find vs index?
Both return the position; when the text isn't found, find returns −1 and index raises ValueError.
String formatting ways?
f-strings f"{x:.2f}" (best), "{}".format(x), "%d" % x.
How do you sort a string?
"".join(sorted(s)). sorted returns a list. sorted(words, key=str.lower) sorts case-insensitively.
⭐ break vs continue vs pass?
break exits the loop; continue skips to the next iteration; pass does nothing (a placeholder).
Loop else?
Runs only if the loop finished without break.
range(2, 10, 3)?
2, 5, 8. Stop is excluded.
for vs while?
for iterates over a sequence (known number of items); while repeats while a condition is true (unknown count).
Ternary operator?
x if cond else y.
Unit 2: Data structures, functions, files
⭐ List vs tuple vs set vs dict?
List: ordered, mutable, allows duplicates []. Tuple: ordered, immutable (). Set: unordered, unique, mutable {}. Dict: key→value, keys unique and hashable, insertion-ordered since 3.7.
⭐ Why use a tuple?
Fixed data that shouldn't change, can be a dict key (it's hashable), slightly faster and lighter, returns multiple values from a function.
append vs extend vs insert?
append(x) adds one item (a list becomes nested); extend(iter) adds each item; insert(i, x) adds at a position.
remove vs pop vs del?
remove(value) deletes the first match; pop(i) removes and returns (default last); del lst[i] deletes by index or slice.
sort() vs sorted()?
sort() works in place on lists and returns None; sorted() returns a new list and works on any iterable.
⭐ d[key] vs d.get(key)?
d[key] raises KeyError if the key is missing; get returns None or a default.
Iterating a dict?
for k in d, d.keys(), d.values(), for k, v in d.items().
Set operations?
| union, & intersection, - difference, ^ symmetric difference. remove raises if missing, discard doesn't. Empty set is set(), not {} (that's a dict).
List comprehension?
[expr for x in iterable if cond]. There are dict and set versions too.
⭐ Parameters vs arguments?
Parameters are the names in the definition; arguments are the actual values passed. Kinds: positional, keyword, default, *args (tuple), **kwargs (dict).
⭐ Mutable default argument trap?
def f(x, lst=[]): the list is created once at definition time and shared across calls. Fix: lst=None then if lst is None: lst = []. (MiniLang's run(variables=None) does exactly this.)
⭐ Local vs global scope, LEGB?
Name lookup order: Local → Enclosing → Global → Built-in. Assigning inside a function makes a local unless you declare global x (or nonlocal x for enclosing).
return vs print?
return sends a value back to the caller; print only displays it. A function with no return gives None.
lambda?
An anonymous one-expression function: lambda a, b: a + b. Used with sorted(key=...), map, filter.
⭐ Module vs package vs library?
Module: one .py file. Package: a folder of modules (traditionally with __init__.py). Library: a collection of packages (NumPy).
import x vs from x import y vs import x as z?
Whole module (use x.y) vs a specific name (use y) vs an alias.
⭐ What is pip?
Python's package installer from PyPI: pip install requests, pip list, pip uninstall, pip freeze > requirements.txt.
if __name__ == "__main__":?
That code runs only when the file is executed directly, not when it's imported.
⭐ File modes?
r read (default), w write (truncates), a append, x create, b binary, + read and write.
⭐ Why use with open(...)?
It's a context manager that closes the file automatically, even on errors.
read() vs readline() vs readlines()?
Whole file as a string / one line / a list of all lines.
csv module?
csv.reader/csv.writer work with lists; DictReader/DictWriter work with dicts. Open with newline="". All values come back as strings.
⭐ try / except / else / finally?
try: risky code. except: handles an error. else: runs if there was no error. finally: always runs (cleanup). raise throws an error. Custom: class MyError(Exception).
Common exceptions?
ValueError, TypeError, KeyError, IndexError, ZeroDivisionError, FileNotFoundError, NameError, AttributeError, ImportError.
Syntax error vs exception?
A syntax error is found while parsing, so the code never runs. An exception happens while it's running.
Clean code?
PEP 8: snake_case variables and functions, PascalCase classes, UPPER_CASE constants, 4-space indents, meaningful names, small functions, docstrings, comments explain *why*.
Debugging techniques?
Read the traceback bottom-up, print, assert, the IDE debugger (breakpoints, step over/into, watch variables), breakpoint()/pdb.
⭐ What is an API? JSON?
API: an interface one program uses to talk to another (web APIs over HTTP). JSON: a text data format of key-value pairs and arrays. json.loads(str) → dict, json.dumps(dict) → str. requests.get(url).json().
HTTP status codes?
200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Server Error.
GET vs POST?
GET fetches data (parameters go in the URL); POST sends data (in the body).
Unit 3: NumPy, Pandas, visualization
⭐ Why is NumPy faster than lists?
Contiguous memory, a single dtype, operations written in C (vectorization, so no Python loop), broadcasting.
Ways to create arrays?
np.array, zeros, ones, arange, linspace, eye, random.rand / default_rng().integers, full.
shape, ndim, size, dtype?
Dimensions tuple, number of axes, total elements, element type.
⭐ arange vs linspace?
arange(start, stop, step) takes a step and excludes stop; linspace(start, stop, num) takes a count and includes stop.
⭐ What is broadcasting?
Doing maths between arrays of different shapes by "stretching" the smaller one (e.g. a matrix plus a row vector).
axis=0 vs axis=1?
axis=0 goes down the rows (one result per column); axis=1 goes across the columns (one result per row).
⭐ * vs @ / np.dot?
* is element-wise; @ is matrix multiplication.
Boolean masking?
a[a > 5] selects the elements where the condition is True.
reshape?
Changes shape without changing the data; -1 means "infer this one". The total size must match.
View vs copy?
A slice is a view (changing it changes the original); .copy() makes an independent array.
⭐ Series vs DataFrame?
A Series is a 1-D labelled array (one column); a DataFrame is a 2-D table of Series sharing an index.
⭐ loc vs iloc?
loc selects by label/name (inclusive slice); iloc selects by integer position (exclusive slice).
First looks at a dataset?
head(), tail(), info(), describe(), shape, columns, dtypes, isna().sum(), value_counts().
⭐ Handling missing data?
isna() / isnull() to find; dropna() to remove; fillna(value / mean / median / ffill) to fill.
Filtering rows?
df[df["marks"] > 80]. Combine with & and | and wrap each condition in brackets.
⭐ groupby?
Split, apply, combine: df.groupby("dept")["marks"].mean(), .agg(...).
merge vs concat?
merge joins on key columns (like SQL JOIN); concat stacks frames along an axis.
Reading/writing files?
pd.read_csv / read_excel / read_json, df.to_csv("f.csv", index=False).
⭐ Matplotlib vs Seaborn?
Matplotlib is the low-level base library with full control. Seaborn is built on Matplotlib: high-level, statistical, nicer defaults, and works directly with DataFrames.
pyplot vs object-oriented style?
plt.plot() acts on the "current" figure; fig, ax = plt.subplots(); ax.plot() controls figures and axes explicitly (better with several plots).
⭐ Which plot for what?
Line: trend over time. Bar: compare categories. Histogram: distribution. Scatter: relationship between 2 variables. Box: median, quartiles, outliers. Pie: parts of a whole. Heatmap: correlation matrix.
Seaborn functions?
histplot, kdeplot, boxplot, violinplot, barplot, countplot, scatterplot, lineplot, regplot, heatmap, pairplot.
Saving a plot?
plt.savefig("x.png", dpi=150) before plt.show().
Unit 4: AI concepts & neural networks
⭐ Define AI.
Making machines do tasks that need human intelligence: learning, reasoning, perception, language, decision making. Term coined by John McCarthy in 1956.
⭐ AI vs ML vs DL?
AI is the broad goal. ML is a subset where systems learn from data without being explicitly programmed. DL is a subset of ML using multi-layer neural networks.
⭐ Types of AI?
By capability: Narrow (all AI today), General, Super. By functionality: reactive, limited memory, theory of mind, self-aware.
⭐ Types of ML?
Supervised (labelled data: classification, regression). Unsupervised (no labels: clustering, dimensionality reduction). Reinforcement (agent learns from rewards).
Turing test?
Alan Turing, 1950: a machine passes if a human judge can't tell its text replies from a human's.
Applications?
Healthcare, recommendations, chatbots/NLP, computer vision, self-driving, fraud detection, speech assistants, translation.
AI concerns?
Bias, privacy, explainability ("black box"), job displacement, misuse, accountability.
⭐ What is an artificial neuron?
It takes inputs × weights, adds a bias, passes the sum through an activation function: y = f(w·x + b). Inspired by biological neurons (dendrites, soma, axon).
⭐ Role of weights and bias?
Weights set how important each input is. Bias shifts the threshold or decision boundary. Both are learned during training.
⭐ Why activation functions?
They add non-linearity. Without them, any number of layers collapses to a single linear function.
⭐ Common activations?
Step (0/1, perceptron). Sigmoid (0..1, binary output). Tanh (−1..1). ReLU max(0, x) (hidden layers, fast, avoids vanishing gradients). Softmax (multi-class probabilities that sum to 1).
⭐ What is a perceptron? Limitation?
A single-layer neuron with a step activation (Rosenblatt, 1958). It can only learn linearly separable problems: AND and OR yes, XOR no. That needs a hidden layer.
⭐ Layers of a neural network?
Input layer (features), hidden layer(s) (learn patterns), output layer (prediction). "Deep" means many hidden layers.
⭐ Forward vs backpropagation?
Forward: inputs flow through the layers to produce a prediction. Backprop: the error flows backwards, using the chain rule to compute each weight's gradient.
⭐ Loss function?
Measures prediction error. MSE for regression, cross-entropy for classification.
⭐ Gradient descent?
Repeatedly update w = w − learning_rate × gradient to walk downhill on the loss.
Learning rate?
The step size. Too large overshoots or diverges; too small trains slowly.
Epoch / batch / iteration?
Epoch: one pass over all the data. Batch: a subset of samples used per update. Iteration: one update.
⭐ Overfitting vs underfitting?
Overfitting memorises the training data and does badly on new data (fix: more data, regularization, dropout, early stopping). Underfitting means the model is too simple and does badly everywhere.
Types of neural networks?
Feedforward/MLP, CNN (images), RNN/LSTM (sequences), Transformer (language, as in GPT), GAN (generation).
⭐ What is a chatbot? Types?
A program that talks with users. Rule-based chatbots match keywords or patterns to scripted replies (ELIZA, 1966): predictable, but limited. AI-based chatbots learn intents from data or use LLMs to generate replies: flexible, but need data or compute.
⭐ Chatbot pipeline?
Input → preprocess (lowercase, remove punctuation, tokenize) → intent detection → entity extraction → response selection or generation → keep context/memory.
What is an intent?
The goal behind a message (greet, ask_price, bye), detected via keywords or a trained classifier.
NLP basics?
Tokenization, stop-word removal, stemming/lemmatization, bag-of-words, TF-IDF, embeddings.