Python for AI & Data Analytics MCQs for NSCT

By the NSCT Exam Editorial Team · Updated 2026-11-24 · Facts checked against official sources on 2026-11-24

Python for AI & Data Analytics is the third topic in the NSCT's AI, Machine Learning & Data Analytics area. It tests whether you can read and predict short code using the four standard libraries: NumPy for arrays, pandas for tables, Matplotlib for plots and scikit-learn for models. The whole area carries 10% of the test, according to HEC's Areas of Competencies.

Expect "what does this code print?" questions. They count as application or analysis items, the two tiers where 2026 candidates scored 45.1% and 44.8% in the HEC NSCT report. Every code output below was run on NumPy 2.5 and pandas 3.0.

NumPy

NumPy's ndarray is an n-dimensional array that holds one data type (dtype) in contiguous memory. Operations run in compiled C loops, which is called vectorisation, so they are far faster than Python loops over lists.

import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a * 10)                      # [[10 20] [30 40]]  element-wise
print(a.mean(axis=1))              # [1.5 3.5]  one value per row
print(a + np.array([100, 200]))    # [[101 202] [103 204]]  broadcasting

The axis you pass is the one that disappears: axis=0 gives one result per column, axis=1 one per row. Broadcasting stretches dimensions of size 1 so that shapes such as (2, 2) and (2,) can be combined.

Exam angle: basic slices such as a[1:3] are views, so writing to them changes the original. Boolean and integer-array indexing return copies.

Pandas

pandas adds labelled data. A Series is a one-dimensional labelled array; a DataFrame is a table of Series that share a row index.

import pandas as pd
df = pd.DataFrame({"name": ["Ali", "Sara", "Omar", "Hina"],
                   "city": ["Lahore", "Karachi", "Lahore", "Multan"],
                   "marks": [72, None, 85, 64]})
print(df["marks"].isnull().sum())                    # 1
print(df[df["marks"] > 70]["name"].tolist())         # ['Ali', 'Omar']
print(df.groupby("city")["marks"].mean().to_dict())

The last line prints {'Karachi': nan, 'Lahore': 78.5, 'Multan': 64.0}: Karachi's only mark is missing, so its group mean is NaN.

Task Method
Select by label df.loc[row_label, "col"]
Select by position df.iloc[0, 2]
Find missing values df.isnull() or df.isna()
Drop or fill missing df.dropna(), df.fillna(value)
Group and aggregate df.groupby("key")["col"].mean()
Combine tables df.merge(other, on="key", how="inner")

Exam angle: pandas skips NaN in mean() and sum() by default, and aligns Series on their index labels before arithmetic, filling unmatched labels with NaN.

Matplotlib

Matplotlib draws charts. The quick pyplot style calls plt.plot(x, y) and plt.show(); the object-oriented style starts with fig, ax = plt.subplots() and then calls ax.plot(), ax.set_xlabel() and so on.

Chart Call Shows
Line plt.plot(x, y) Trend over an ordered variable such as time
Scatter plt.scatter(x, y) Relationship between two numeric variables
Histogram plt.hist(x, bins=10) Distribution of one numeric variable
Bar plt.bar(labels, values) Comparison across categories

Exam angle: match the chart to the question asked. "Distribution of marks" means histogram, "relationship between study hours and marks" means scatter.

Scikit-learn

scikit-learn gives every model the same interface. Estimators have fit(X, y) to learn and predict(X) to infer. Transformers such as StandardScaler have fit(), transform() and fit_transform(). X must be 2-D with shape (n_samples, n_features); one feature stored as a 1-D array needs x.reshape(-1, 1).

A typical flow: split with train_test_split (the default test share is 0.25), fit the scaler on the training set only, transform both sets with it, fit the model and score it on the test set. A Pipeline bundles these steps so the scaler can never see test rows.

Exam angle: fitting a scaler or imputer on the full dataset before splitting is data leakage, and the reported score will be optimistic.

Common traps

Worked examples

1. Understanding. Which pandas object would you use to hold a table of student names, cities and marks? Answer: a DataFrame. Its columns can have different types, while a NumPy array would force one dtype on everything.

2. Application. What does np.array([[1, 2, 3], [4, 5, 6]])[:, 1] return? Answer: [2 5]. The colon takes every row and 1 takes the second column, giving one value from each row.

3. Analysis. A Series is created as s = pd.Series([5, 6, 7], index=[1, 2, 3]). A student expects s.loc[1] and s.iloc[1] to be equal. What do they return? Answer: 5 and 6. loc looks up the label 1, which is the first element, while iloc uses position 1, which is the second element. They only agree when the index is the default 0, 1, 2.

Practise

The quiz below has 100 questions on this topic, which you can filter by tier and difficulty.

Practise: 100 questions

Interactive quiz loading. The first 10 questions are shown below.

  1. What is the core data structure provided by NumPy?

    1. DataFrame, a labelled table of columns
    2. Series, a labelled one-dimensional column
    3. Figure, a container for plots
    4. ndarray, an n-dimensional array of elements of one data type
    Show answer

    Answer: D. ndarray, an n-dimensional array of elements of one data type

    NumPy is built around the ndarray: a fixed-size, homogeneous, n-dimensional array. DataFrame and Series come from pandas, and Figure comes from Matplotlib.

  2. In pandas, what is a DataFrame?

    1. A two-dimensional labelled table whose columns can hold different data types
    2. A one-dimensional labelled array
    3. A NumPy array that can only hold numbers
    4. A plotting object for line charts
    Show answer

    Answer: A. A two-dimensional labelled table whose columns can hold different data types

    A DataFrame is a 2-D table with a row index and named columns; each column is a Series and columns may have different dtypes (numbers, text, dates). A one-dimensional labelled array is a Series.

  3. What is the difference between df.loc and df.iloc in pandas?

    1. loc selects by index labels; iloc selects by integer position
    2. loc selects by integer position; iloc selects by index labels
    3. loc selects columns only; iloc selects rows only
    4. There is no difference; they are aliases
    Show answer

    Answer: A. loc selects by index labels; iloc selects by integer position

    loc uses the labels in the index and column names, and its slices include the end label. iloc uses 0-based integer positions like Python lists, and its slices exclude the end position.

  4. What does broadcasting mean in NumPy?

    1. Sending an array to several CPU cores at once
    2. Converting a list into an array
    3. Printing an array with all its elements
    4. Automatically stretching arrays of compatible shapes so element-wise operations work without copying data
    Show answer

    Answer: D. Automatically stretching arrays of compatible shapes so element-wise operations work without copying data

    When shapes differ, NumPy compares them from the trailing dimension; sizes must be equal or 1. Dimensions of size 1 are virtually repeated, so an array of shape (2, 1) plus one of shape (3,) gives shape (2, 3).

  5. For a 2-D NumPy array, what does arr.sum(axis=0) compute?

    1. The sum of each row (collapsing the columns)
    2. The sum of every element
    3. The sum of each column (collapsing the rows)
    4. The sum of the first row only
    Show answer

    Answer: C. The sum of each column (collapsing the rows)

    The axis you pass is the one that disappears. axis=0 runs down the rows, giving one total per column; axis=1 runs across the columns, giving one total per row; no axis sums everything.

  6. Which pandas method returns a Boolean mask that is True where values are missing (NaN or None)?

    1. dropna()
    2. fillna()
    3. isnull()
    4. describe()
    Show answer

    Answer: C. isnull()

    isnull() (alias isna()) marks missing values with True. Calling .sum() on it counts missing values per column. dropna() removes them and fillna() replaces them.

  7. Why are NumPy array operations usually much faster than equivalent Python loops over lists?

    1. NumPy uses the GPU by default
    2. Python lists cannot store numbers
    3. Arrays store one data type in contiguous memory and operations run in compiled C loops (vectorisation)
    4. NumPy arrays are always smaller than 1 KB
    Show answer

    Answer: C. Arrays store one data type in contiguous memory and operations run in compiled C loops (vectorisation)

    A list holds pointers to separate Python objects, so each step of a loop does type checks. An ndarray holds raw values of one dtype side by side, and vectorised operations process them in optimised C code. NumPy runs on the CPU unless you use another library.

  8. In Matplotlib's pyplot interface, which call displays the figure window?

    1. plt.show()
    2. plt.display()
    3. plt.render()
    4. plt.open()
    Show answer

    Answer: A. plt.show()

    plt.show() renders and displays all open figures. In Jupyter, figures often appear automatically, but plt.show() is the standard call in scripts. plt.savefig() writes the figure to a file.

  9. What does fig, ax = plt.subplots() return?

    1. Two Axes objects side by side
    2. A list of colours and a list of markers
    3. A Figure object and an Axes object to draw on
    4. The x data and the y data of the plot
    Show answer

    Answer: C. A Figure object and an Axes object to draw on

    plt.subplots() creates a Figure (the whole canvas) and one or more Axes (individual plots). With nrows or ncols above 1, ax becomes an array of Axes. The object-oriented style then calls ax.plot(), ax.set_title() and so on.

  10. Which plot is best for showing the distribution of a single numeric variable, such as exam marks?

    1. Scatter plot
    2. Pie chart
    3. Line plot of the row index
    4. Histogram
    Show answer

    Answer: D. Histogram

    A histogram bins values and shows how many fall in each bin, revealing shape, spread and skew. A scatter plot shows the relationship between two numeric variables, and pie charts show parts of a whole.

FAQs

Do I need to memorise NumPy and pandas function names for the NSCT?

You need to recognise the common ones and predict what they do: array creation (array, arange, linspace, reshape), axis-based sums and means, Boolean filtering, loc and iloc, isnull, dropna, fillna, groupby and merge. You do not need rarely used arguments. Practising short outputs, as in the quiz below, is the fastest way to make them familiar.

What is the difference between a NumPy array and a pandas DataFrame?

A NumPy array is a block of numbers of one dtype, indexed only by position, and it is the fastest choice for maths. A DataFrame is a labelled table: rows have an index, columns have names and each column can have its own type. pandas is built on NumPy, and df.to_numpy() converts a DataFrame back to an array.

Why does scikit-learn need a 2-D array for X?

Each row of X is one sample and each column one feature, so X always has shape (n_samples, n_features), even with a single feature or a single sample. A 1-D array is ambiguous: it could be one sample with many features or many samples with one feature. Use reshape(-1, 1) for one feature or reshape(1, -1) for one sample.

Is Matplotlib still used when libraries such as seaborn exist?

Yes. Seaborn and the pandas plot() method are built on top of Matplotlib, so understanding figures, axes and the basic chart types helps with all of them. For the NSCT, focus on picking the right chart for a question and knowing that plt.subplots() returns a figure and axes.

Next step

Continue with Data Collection & Pre-processing MCQs, the next official topic, where these pandas skills are put to work on missing values and scaling. Revise Mathematical Foundations if the matrix questions slowed you down, or return to the AI and ML MCQs hub. Then try an NSCT mock test.