WBCHSE HS Artificial Intelligence & Data Science study materials
WBCHSE HS Artificial Intelligence & Data Science study resources

WBCHSE HS Artificial Intelligence & Data Science practice questions

One question at a time. Build your WBCHSE HS Artificial Intelligence & Data Science understanding.

First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

In the imitation game proposed by Alan Turing in 1950, what decides whether a machine is credited with intelligent behaviour?

  1. An interrogator cannot reliably distinguish its replies from a human's. Correct answer.
  2. The machine performs arithmetic faster than a desk calculator.
  3. The machine's internal program is shown to the interrogator for inspection.
  4. The machine stores far more facts than any human specialist.

Explanation

Turing replaced the vague question 'can machines think?' with an operational test: a human judge exchanges text with a hidden human and a hidden machine, and the machine passes if the judge cannot tell them apart. Only observable conversational behaviour counts, so memory size, processing speed and internal design are irrelevant to the verdict.

Question 2Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

Which event is conventionally treated as the founding of artificial intelligence as an academic discipline?

  1. The 1956 Dartmouth Summer Research Project that coined the term 'artificial intelligence'. Correct answer.
  2. The introduction of the backpropagation training algorithm for multilayer networks in 1986.
  3. The defeat of world chess champion Garry Kasparov by the Deep Blue system in 1997.
  4. The publication by Rosenblatt in 1958 of the perceptron, the first trainable neural network model.

Explanation

The Dartmouth Summer Research Project of 1956, organised by McCarthy, Minsky, Rochester and Shannon, is conventionally credited with naming the field and setting its research agenda, including the conjecture that every feature of learning could be described precisely enough for a machine to simulate it. The perceptron, backpropagation and Deep Blue are later milestones inside an already existing discipline.

Question 3Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

In artificial intelligence terminology, a system counts as an intelligent agent when it:

  1. perceives through sensors and acts through actuators to pursue goals. Correct answer.
  2. has been trained on a large dataset labelled by human domain experts.
  3. stores its knowledge in a well-normalised relational database.
  4. runs on hardware that is faster and more reliable than a conventional computer.

Explanation

An agent is defined by its relationship to an environment: it receives percepts through sensors, acts on the environment through actuators, and is called intelligent or rational when those actions aim at a goal or performance measure. Speed, storage technology and the source of training data describe how a system is built, not whether it is an agent.

Question 4Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

A payroll program computes each salary from fixed tax slabs written by its programmers. An image classifier, by contrast, is given thousands of labelled photographs and learns to label new ones. Which statement best captures the difference?

  1. The payroll program follows programmer-coded rules, while the classifier derives its rules from data. Correct answer.
  2. Both programs are AI systems because both accept data as input and produce output.
  3. The payroll program is an AI system because it automates a task previously done by clerks.
  4. The image classifier is really conventional software because it runs on the same hardware as the payroll program.

Explanation

In conventional computing the solution algorithm is written explicitly: the tax rules exist in the source code and the program applies them deterministically. In machine learning the developer supplies examples and an algorithm that fits a model, so the effective decision rules are inferred from data rather than stated by a person. Shared hardware and the mere processing of input do not distinguish the two.

Question 5Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

A thermostat switches a heater on whenever the measured temperature falls below the set point and off when it rises above it. In agent terminology this controller is best described as:

  1. a goal-based agent, because it persistently pursues the goal of keeping the room comfortable.
  2. a simple reflex agent, because it applies a condition–action rule to the current percept. Correct answer.
  3. a utility-based agent, because it maximises a numerical objective function.
  4. a learning agent, because it gradually improves its behaviour over time.

Explanation

A simple reflex agent selects actions from condition–action rules that look only at the present percept, exactly as the thermostat reacts to the current temperature reading. It keeps no model of the world, compares no alternative futures and never rewrites its own rules, so the richer agent classes do not fit even though the device serves a useful purpose.

Question 6Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

Before designing an automated warehouse robot, a team writes a PEAS description of its task environment. Along with the performance measure, environment and actuators, PEAS requires the team to specify the agent's:

  1. source code structure
  2. power supply rating
  3. sensors Correct answer.
  4. programming language

Explanation

PEAS stands for Performance measure, Environment, Actuators and Sensors, the four items used to specify a task environment completely before any agent design begins. Sensors state what the agent can perceive, actuators what it can do, the environment what it acts within, and the performance measure what counts as success. Language and power supply are implementation choices the framework deliberately leaves out.

Question 7Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

Which statement correctly contrasts a classical rule-based expert system with a machine-learning model?

  1. The expert system generalises to unseen cases better because it needs no stored knowledge base.
  2. Its knowledge is stored as explicit rules, usually elicited from specialists, and its reasoning can be traced. Correct answer.
  3. The expert system learns its rules automatically from raw sensor data with no human intervention.
  4. The expert system must first be trained on a large labelled dataset of solved cases before it can reason at all.

Explanation

In a rule-based expert system the knowledge base is hand-crafted, typically through knowledge elicitation from human specialists, and the inference engine applies those rules, so a conclusion can be traced back to the rules that produced it. Machine-learning models instead fit parameters from data and generally offer far weaker direct traceability. The remaining options describe learning systems rather than rule-based ones.

Question 8Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

Two vacuum-cleaning agents are compared. Agent A cleans every dirty square but uses twice the electricity and time of Agent B, which leaves one square dirty. How should a rational-agent designer choose between them?

  1. Agent A, because the definition of rationality requires the environment to be left completely clean at all times.
  2. Agent B, because using less electricity is always the dominant performance measure in agent design.
  3. Agent A, because a rational agent must maximise the correctness of every individual action it takes.
  4. It depends on the performance measure, which weights dirt removed against electricity and time used. Correct answer.

Explanation

Rationality is defined only relative to a performance measure, so the two agents cannot be ranked until that measure states how cleanliness is traded against energy and time. If cleanliness dominates, Agent A wins; if resource cost is weighted heavily, Agent B may win. Neither behaviour is rational in the abstract, and maximising per-action correctness is not the definition of rationality.

Question 9Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

Historians of AI generally attribute the first 'AI winter' of the 1970s to which combination of causes?

  1. The publication of the Turing Test, which convinced research funders that machines could never think.
  2. Disappointment after early promises, combinatorial explosion in search, and funding cuts after reports such as Lighthill's. Correct answer.
  3. The invention of the transistor, which made electronic computers far too expensive for university laboratories.
  4. The collapse of the internet bubble, which removed private investment from almost all software companies.

Explanation

Early optimism about machine translation and general problem solving met tasks that did not scale, because search spaces grew combinatorially while computing power remained limited. Critical assessments, most visibly the 1973 Lighthill report in the United Kingdom, were followed by sharp reductions in funding, producing the retrenchment now called the first AI winter. The other options involve events that either enabled computing or occurred decades later.

Question 10Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

A delivery robot keeps an internal map of the building, updates it when a corridor turns out to be blocked, and predicts battery drain before choosing a route. Which agent description fits best, and why?

  1. Model-based agent, because it maintains internal state about the world to cope with partial observability. Correct answer.
  2. Simple reflex agent, because it reacts to blocked corridors as soon as they are detected.
  3. Learning agent, because updating a map from new observations is a form of learning.
  4. Goal-based agent, because it has a destination and therefore needs no internal state at all.

Explanation

The distinguishing feature described is internal state: the robot keeps a representation of the world, including parts it has seen before or cannot currently observe, and revises it as percepts arrive, which is what makes an agent model-based. Predicting battery drain is also reasoning about how the world evolves over time. Goal-seeking or learning may coexist, but the capability under test is maintaining a world model under partial observability.

Question 11Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

In the taxonomy used by Russell and Norvig, definitions of artificial intelligence are organised along two axes. Which pair of axes is used?

  1. Hardware versus software, each judged against speed or memory limits
  2. Symbolic versus connectionist methods, each judged against training time
  3. Thought versus behaviour, each judged against human or rational standards Correct answer.
  4. Supervised versus unsupervised learning, each judged against labelled data

Explanation

The taxonomy crosses two questions: does the system think or act, and is the standard human performance or rational performance? This yields four families of definitions: thinking humanly, acting humanly, thinking rationally and acting rationally. The other pairs describe implementation choices or learning paradigms rather than the definition of intelligence itself.

Question 12Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

Chess programs that beat grandmasters are now rarely praised as 'AI' by the public, because the feat has become ordinary. What name do AI textbooks give to this tendency to reclassify solved problems as mere computing?

  1. The frame problem
  2. The AI effect Correct answer.
  3. The combinatorial explosion
  4. The symbol grounding problem

Explanation

The AI effect describes how each successful AI capability is eventually absorbed into ordinary software and stops being labelled intelligent. It explains why the perceived boundary of AI keeps moving forward. The other terms name distinct technical problems in knowledge representation and search.

Question 13Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

In AI problem solving, what is a heuristic?

  1. A complete listing of every state reachable in a search space
  2. A proof that a search algorithm always returns the optimal solution
  3. A hardware accelerator used only for training neural networks
  4. A rule of thumb that usually finds a good solution quickly but gives no guarantee of optimality Correct answer.

Explanation

A heuristic is an informed guess, such as estimated distance to the goal, that guides search toward promising regions. It trades guarantees of completeness or optimality for practical speed. A complete state listing is instead the state space itself, and a guarantee of optimality comes from an algorithm's proof, not from a heuristic.

Question 14Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

A chess-playing agent can see the entire board, moves alternate, and the effect of each move is fixed by the rules. Which environment description fits this agent?

  1. Partially observable, stochastic, episodic, continuous
  2. Fully observable, stochastic, sequential, dynamic
  3. Partially observable, deterministic, episodic, continuous
  4. Fully observable, deterministic, sequential, discrete Correct answer.

Explanation

Chess is fully observable because every piece is visible, and deterministic because legal moves have fixed effects. It is sequential because earlier moves constrain later ones, and discrete because positions and moves form countable sets. Stochastic and continuous descriptions fit domains such as robot navigation in the real world.

Question 15Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

A taxi agent can follow several valid routes. It scores each route on estimated travel time, fuel cost and passenger comfort, then chooses the route with the best overall score. Which agent type does this illustrate?

  1. Simple reflex agent
  2. Goal-based agent
  3. Table-driven agent
  4. Utility-based agent Correct answer.

Explanation

A utility-based agent uses a utility function to compare outcomes that all satisfy the goal, choosing the one with the highest expected utility. Here time, fuel and comfort are combined into a single score. A goal-based agent would only distinguish reaching the destination from failing to reach it.

Question 16Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

Which statement best expresses what it means for an agent to be rational at a given moment?

  1. It chooses the action expected to maximise its performance measure, given its percept sequence and built-in knowledge Correct answer.
  2. It always chooses the action that turns out best once the outcome is known
  3. It has complete knowledge of every future state of its environment
  4. It selects actions at random so that no outcome can be predicted

Explanation

Rationality concerns the best expected outcome given the information available, not the best outcome in hindsight. An agent cannot be faulted for an unlucky result if its choice was optimal under its percepts and prior knowledge. Omniscience and randomness are separate ideas that do not define rationality.

Question 17Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

Which contrast correctly distinguishes symbolic AI from connectionist AI?

  1. Symbolic AI cannot represent knowledge, while connectionist AI stores facts in relational databases
  2. Symbolic AI runs only on GPUs, while connectionist AI runs only on CPUs
  3. Symbolic AI learns only from raw pixels, while connectionist AI relies on hand-written rules
  4. Symbolic AI represents knowledge as explicit rules and symbols, while connectionist AI uses distributed numerical weights learned from data Correct answer.

Explanation

Symbolic AI, often called classical or rule-based AI, encodes knowledge in explicit structures such as logic rules and frames. Connectionist AI, exemplified by neural networks, distributes knowledge across numerical weights adjusted by learning. The two traditions differ in representation, not in which hardware they require.

Question 18Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

Searle's Chinese room argument is intended to establish which point about artificial intelligence?

  1. That natural language can never be processed by any computer program
  2. That machines become conscious automatically once their rule books grow large enough
  3. That the Turing test is a perfectly reliable measure of understanding
  4. That rule-governed symbol manipulation does not by itself produce semantic understanding Correct answer.

Explanation

In the thought experiment a person follows English rules to produce convincing Chinese replies without understanding Chinese. Searle concludes that passing a linguistic test does not prove that the system understands meaning. The argument therefore challenges strong claims that a running program suffices for a mind.

Question 19Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

In agent design, what is the relation between an agent program and an agent function?

  1. The program is the concrete implementation on an architecture; the function is the abstract percept-to-action mapping Correct answer.
  2. The program is the abstract mathematical mapping; the function is the written source code
  3. The two terms are exact synonyms and are used interchangeably in every AI textbook
  4. The function is the physical hardware; the program is the set of sensors and actuators

Explanation

The agent function is a mathematical description that maps every possible percept sequence to an action. The agent program is the real code that, running on an architecture such as a CPU, computes that function for the percepts actually received. Keeping the abstract specification separate from the implementation is central to agent design.

Question 20Introduction to Artificial Intelligence: history, definitions, AI vs. conventional computing, intelligent agents

Which statement best distinguishes weak AI from strong AI?

  1. Weak AI requires quantum computers, while strong AI runs on ordinary hardware
  2. Weak AI claims machines already possess consciousness, while strong AI denies that they can
  3. Weak AI treats machines as simulators of intelligent behaviour, while strong AI holds that a suitable machine can have a genuine mind Correct answer.
  4. Weak AI applies only to robots, while strong AI applies only to software programs

Explanation

The weak AI position uses computers as tools to model or simulate cognition without claiming real understanding. The strong AI position asserts that an appropriately programmed machine literally has a mind and mental states. The debate is philosophical, and hardware type or embodiment is irrelevant to it.

Question 21Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A data-science script must store a fixed record of feature names that must never be altered after creation. Which built-in Python type holds an ordered sequence whose elements cannot be reassigned?

  1. tuple Correct answer.
  2. list
  3. bytearray
  4. dictionary

Explanation

A tuple is immutable: once created, assigning to an existing position such as t[0] = 5 raises a TypeError. Lists and bytearrays are mutable sequence types whose elements can be changed in place, and dictionaries support item assignment by key. Immutability makes tuples safe for fixed records such as column-name sets that other code should not accidentally modify.

Question 22Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A loop written as `for i in range(2, 10, 3):` is used to step through sample indices. Which values of `i` are produced?

  1. 2, 5, 8 Correct answer.
  2. 2, 3, 4, 5, 6, 7, 8, 9
  3. 2, 4, 6, 8
  4. 3, 6, 9

Explanation

range(start, stop, step) begins at start, adds step each time, and stops before reaching stop. Starting at 2 with step 3 gives 2, then 5, then 8; the next value 11 is not less than 10, so the sequence ends. Omitting the step, as in range(2, 10), would instead produce every integer from 2 up to 9.

Question 23Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

After `import numpy as np`, the statement `a = np.array([[1, 2, 3], [4, 5, 6]])` is executed. What does `a.shape` return?

  1. (2, 3) Correct answer.
  2. (3, 2)
  3. 2
  4. (6,)

Explanation

A NumPy array built from a nested list keeps the nested structure, so shape is reported as a tuple of lengths per axis. There are 2 rows and 3 columns, so a.shape is (2, 3). The value 2 would be returned by a.ndim, which counts dimensions rather than reporting their sizes.

Question 24Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A pandas DataFrame `df` is indexed by student roll numbers 101, 102, 103, ... (set with set_index). Which expression selects the row labelled 103 by its index label?

  1. df.loc[103] Correct answer.
  2. df.take(103)
  3. df.iloc[103]
  4. df[103]

Explanation

The .loc indexer works on index labels, so df.loc[103] returns the row whose label is 103 as a Series. The .iloc indexer and take() work on integer positions, which here are unrelated to the roll-number labels. Plain bracket indexing with an integer on a DataFrame is treated as a column lookup, not a row label lookup.

Question 25Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

Consider `a = np.arange(5)` followed by `b = a[1:4]` and then `b[0] = 99`. What is the final content of `a`?

  1. [ 0 1 99 3 4]
  2. [99 1 2 3 4]
  3. [ 0 99 2 3 4] Correct answer.
  4. [ 0 1 2 3 4]

Explanation

Basic slicing of a NumPy array returns a view that shares the original data buffer rather than a copy. Writing to b[0] therefore writes to position 1 of a, giving [0, 99, 2, 3, 4]. Calling b = a[1:4].copy() would have produced an independent array and left a unchanged.

Question 26Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

In Python, what happens to the `else` suite attached to a `for` loop?

  1. It runs when the loop ends without hitting a break. Correct answer.
  2. It runs once before the first iteration starts.
  3. It runs only when the iterable passed in is empty.
  4. It runs only after the loop body raises an error.

Explanation

A loop's else suite executes when the iterable is exhausted normally, which makes it useful for search loops that need a not-found branch. If a break statement fires inside the loop, the else suite is skipped entirely. Exceptions propagate out of the loop and do not trigger the else suite.

Question 27Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

You build a plot with `fig, ax = plt.subplots()` from Matplotlib's pyplot module. Which statement sets the label 'Epoch' on the horizontal axis of that plot?

  1. ax.set_xlabel('Epoch') Correct answer.
  2. ax.xlabel('Epoch')
  3. fig.set_xlabel('Epoch')
  4. plt.xlabel(ax, 'Epoch')

Explanation

In the object-oriented interface, Axes objects expose setter methods, so ax.set_xlabel('Epoch') labels the horizontal axis of that specific axes. The figure-level object has no set_xlabel method, and plt.xlabel('Epoch') acts on the current axes rather than a chosen one. Using the ax object is preferred when several subplots exist because the target is unambiguous.

Question 28Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A DataFrame `df` has columns 'dept' and 'salary'. What does `df.groupby('dept')['salary'].mean()` return?

  1. A Series of department means indexed by dept. Correct answer.
  2. A DataFrame that keeps every original column.
  3. A DataFrame with mean salaries in positional order.
  4. One float for the mean salary of the whole table.

Explanation

Selecting a single column after groupby reduces the result to a Series whose index holds the distinct department names and whose values hold each group's mean salary. Column selection before aggregation prevents pandas from returning a one-column DataFrame. The result is aggregated, so the original row count and extra columns are not preserved.

Question 29Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A function is defined as `def add_item(item, cart=[]):` and its body runs `cart.append(item); return cart`. The calls `add_item('pen')` and then `add_item('book')` are made. What does the second call return?

  1. ['pen', 'book'] Correct answer.
  2. ['pen']
  3. ['book', 'pen']
  4. ['book']

Explanation

Default argument values are evaluated once, when the def statement executes, so the same list object is reused across every call that omits cart. The first call appends 'pen' to that shared list, and the second appends 'book' to the same object, returning ['pen', 'book']. The standard fix is to default to None and create a fresh list inside the function body.

Question 30Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

Which pair of NumPy array shapes can be combined with the element-wise `*` operator without raising a ValueError?

  1. (2, 3) and (2, 2)
  2. (2, 3) and (2,)
  3. (2, 3) and (3, 2)
  4. (2, 3) and (3,) Correct answer.

Explanation

Broadcasting compares shapes from the trailing axis and requires either equal sizes or a size of 1. With (2, 3) and (3,), the trailing 3 matches 3 and the shorter shape is stretched along the leading axis, giving a (2, 3) result. Any pair whose trailing dimensions disagree, such as 3 against 2, fails with a ValueError.

Question 31Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

In a Python script for a data-science project, which literal directly creates a dictionary that maps feature names to default values?

  1. ['age', 'income']
  2. {'age', 'income'}
  3. ('age', 'income')
  4. {'age': 0} Correct answer.

Explanation

A dictionary literal uses curly braces with comma-separated key: value pairs. Square brackets create a list, parentheses create a tuple, and curly braces containing only values create a set rather than a mapping.

Question 32Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A data-cleaning loop uses `while` and contains a `break` statement inside an `if`. What is the effect when that `break` executes?

  1. It skips the rest of the current iteration and continues the loop.
  2. It restarts the loop from its first statement.
  3. It terminates the entire Python program.
  4. It exits the nearest enclosing loop immediately. Correct answer.

Explanation

`break` transfers control out of the innermost loop that contains it, ending that loop immediately. The `continue` statement is the one that skips only the rest of the current iteration.

Question 33Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A helper function used in an AI script is defined with `def score(x):` and a body that prints a value but has no `return` statement. What does a call to `score(5)` evaluate to?

  1. An empty string
  2. 0
  3. The last printed value
  4. None Correct answer.

Explanation

When a Python function finishes without executing a `return` statement, it implicitly returns the special value `None`. Printing a value inside the function does not change what the call evaluates to.

Question 34Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

After `import numpy as np`, which call produces a one-dimensional NumPy array of exactly five values spaced evenly from 0 to 1, including both endpoints?

  1. np.arange(0.0, 1.0, 0.25)
  2. np.zeros(5)
  3. np.linspace(0, 1, 5) Correct answer.
  4. np.ones(5)

Explanation

`np.linspace(start, stop, num)` returns exactly `num` evenly spaced values and includes the stop value by default. The call `np.arange(0.0, 1.0, 0.25)` uses a step of 0.25 and therefore produces only four values, 0.0 through 0.75.

Question 35Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A pandas DataFrame `df` contains 500 student records. What does the expression `df.head(3)` return?

  1. The first three rows of `df` Correct answer.
  2. A statistical summary of the first three columns
  3. The first three columns of `df`
  4. The last three rows of `df`

Explanation

`DataFrame.head(n)` returns the first `n` rows using positional row selection. The `tail` method returns the last rows, and `describe` returns summary statistics rather than a row subset.

Question 36Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

In Matplotlib's pyplot module, which function draws a histogram of a one-dimensional numeric array named `values`?

  1. plt.plot(values)
  2. plt.hist(values) Correct answer.
  3. plt.scatter(values)
  4. plt.bar(values)

Explanation

`plt.hist` bins numeric data and draws the frequency distribution as bars. `plt.plot` draws a line, `plt.scatter` expects x and y coordinates, and `plt.bar` expects positions and heights.

Question 37Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A DataFrame `df` has a numeric column `marks`. Which expression returns only the rows where `marks` is greater than 80?

  1. df.loc['marks'] > 80
  2. df[df['marks'] > 80] Correct answer.
  3. df.drop('marks' > 80)
  4. df['marks'] > 80

Explanation

Placing a boolean Series inside square brackets filters the DataFrame and keeps rows where the condition is True. The comparison by itself returns only a boolean Series, and `.loc` with a label selects data rather than applying a row filter.

Question 38Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

For a two-dimensional NumPy array `a` with shape `(3, 4)`, what does `a.sum(axis=0)` return?

  1. A flattened array containing all twelve elements
  2. A single scalar equal to the total of all elements
  3. An array of three values, each summing one row
  4. An array of four values, each summing one column Correct answer.

Explanation

With `axis=0`, NumPy collapses the row axis, so the result has one sum for each column and length 4. Using `axis=1` would collapse the column axis and produce one sum per row.

Question 39Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

Consider this Python program: `x = 10`, then `def f():` with an indented body `x = 5` and `return x`, then `print(f(), x)`. What is printed?

  1. 5 10 Correct answer.
  2. 5 5
  3. 10 10
  4. 10 5

Explanation

The assignment inside `f` creates a new local variable named `x`, so the global `x` stays 10. The function returns the local value 5, and printing both values gives `5 10`.

Question 40Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A pandas Series named `dept` holds department names for many employees. What does `dept.value_counts()` return?

  1. A single count of all non-missing department entries
  2. The employees sorted alphabetically by department
  3. The number of employees in each distinct department Correct answer.
  4. The department name that appears least often

Explanation

`Series.value_counts()` counts how many times each distinct value occurs and returns a Series indexed by those values. It does not return a single total, reorder the original rows, or report only the least common value.

Question 41Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A data-science script collects the distinct class labels seen in a batch with `labels = {'cat', 'dog', 'cat'}`. What is the value of `len(labels)`?

  1. 3
  2. 1
  3. 2 Correct answer.
  4. 4

Explanation

A set literal stores only unique elements, so the repeated `'cat'` appears once and the set contains `'cat'` and `'dog'`. Its length is therefore 2. The braces do not create a list or dictionary here because the entries are bare strings, not key-value pairs.

Question 42Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

An AI project grades predictions with `score = 72`, followed by `if score >= 90: grade = 'A'`, `elif score >= 70: grade = 'B'`, `elif score >= 50: grade = 'C'`, and `else: grade = 'D'`. What is `grade`?

  1. 'C'
  2. 'B' Correct answer.
  3. 'A'
  4. 'D'

Explanation

The `if`/`elif` chain checks conditions from top to bottom and executes only the first true branch. Since 72 is not at least 90 but is at least 70, the second branch assigns `'B'`. Later `elif` branches are skipped.

Question 43Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

In a Matplotlib exploration of two numeric features `x` and `y`, which pyplot call creates a scatter plot showing one marker per observation?

  1. plt.pie(x, labels=y)
  2. plt.hist(x)
  3. plt.scatter(x, y) Correct answer.
  4. plt.bar(x, y)

Explanation

`plt.scatter(x, y)` places one marker at each paired x-y observation, which is the usual way to inspect relationships between two numeric features. Histograms summarize one variable's distribution, while bar and pie charts are used for categorical comparisons or proportions.

Question 44Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

After `import numpy as np`, an array is created with `a = np.array([5, 2, 8, 1])`. Which expression returns a NumPy array containing only the values of `a` that are greater than 5?

  1. a[a > 5] Correct answer.
  2. a[5]
  3. a > 5
  4. a[np.array([True, False, True, False])]

Explanation

`a > 5` produces a Boolean mask whose True positions mark values greater than 5. Using that mask inside `a[...]` selects exactly those elements, giving `array([8])`. The comparison itself returns Booleans rather than the selected values.

Question 45Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A pandas DataFrame `df` is indexed by employee IDs such as 401, 402, and 403. Which expression returns the row at the first physical position, regardless of the index labels?

  1. df[0]
  2. df.loc[0]
  3. df.iloc[0] Correct answer.
  4. df.head(0)

Explanation

`.iloc` selects by zero-based integer position, so `.iloc[0]` always returns the first physical row even when index labels are employee IDs. `.loc` uses labels, and the label `0` is not guaranteed to exist. `head(0)` returns an empty object.

Question 46Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A function is defined with `def summarize(values): return len(values), sum(values) / len(values)`. After `count, mean = summarize([2, 4, 6])`, what are `count` and `mean`?

  1. count = 3, mean = 4.0 Correct answer.
  2. count = 3, mean = 6.0
  3. count = 3, mean = 12.0
  4. count = 6, mean = 4.0

Explanation

The function returns a tuple `(len(values), sum(values) / len(values))`, and the assignment unpacks it into `count` and `mean`. The list has three elements and sums to 12, so `mean` is 4.0. Thus `count` is 3 and `mean` is 4.0.

Question 47Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A pandas DataFrame `df` has a numeric column `price`. Which expression can be assigned to `df['price_with_tax']` to store each price multiplied by 1.18?

  1. df['price'] * 1.18 Correct answer.
  2. df['price'] + 1.18
  3. df['price'] / 1.18
  4. df['price'].apply(lambda p: p + 1.18)

Explanation

In pandas, arithmetic on a Series is vectorized, so `df['price'] * 1.18` produces a Series with each price multiplied by 1.18. Assigning that Series to `df['price_with_tax']` creates the new column with aligned row indices.

Question 48Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

A cleaning loop iterates over records with `for row in records:` and contains `if row['missing']: continue` followed by an append operation. When the condition is true for a row, what happens?

  1. The loop terminates before later records are processed.
  2. The current row is appended before the next iteration.
  3. The `continue` statement raises a runtime exception.
  4. Remaining statements in this iteration are skipped. Correct answer.

Explanation

`continue` ends the current loop iteration immediately and jumps to the next record. Any statements after it in that iteration, including the append operation, are skipped for the flagged row. The loop itself keeps running for later records.

Question 49Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

After `import numpy as np`, an array is defined as `scores = np.array([45, 82, 67, 91])`. What does `np.where(scores >= 60, 'pass', 'fail')` return?

  1. array(['pass', 'fail', 'fail', 'pass'], dtype='<U4')
  2. array(['fail', 'pass', 'pass', 'pass', 'fail'], dtype='<U4')
  3. array([False, True, True, True])
  4. array(['fail', 'pass', 'pass', 'pass'], dtype='<U4') Correct answer.

Explanation

`np.where` evaluates the condition element by element and picks `'pass'` where it is true and `'fail'` where it is false. The comparisons give `[False, True, True, True]`, so the output is `['fail', 'pass', 'pass', 'pass']`. The result is a new NumPy string array.

Question 50Python Programming for AI and Data Science: data types, control flow, functions, libraries (NumPy, pandas, Matplotlib)

Two pandas DataFrames, `students` and `scores`, both contain a column `roll`. Which call returns only the rows whose `roll` value appears in both DataFrames?

  1. pd.merge(students, scores, on='roll', how='outer')
  2. pd.merge(students, scores, on='roll', how='right')
  3. pd.merge(students, scores, on='roll', how='left')
  4. pd.merge(students, scores, on='roll', how='inner') Correct answer.

Explanation

An inner merge keeps only key values that are present in both DataFrames, which is the intersection requested. An outer merge would also keep unmatched rows, while left and right merges retain all rows from one side.