IBM Data Science Professional Certificate study materials
IBM Data Science Professional Certificate study resources

IBM Data Science Professional Certificate practice questions

One question at a time. Build your IBM Data Science Professional Certificate 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 1Data Science Foundations and Methodology

A retail analyst wants to estimate next quarter's revenue using historical sales data. Which statement best describes the role of inferential statistics in this project?

  1. It guarantees that a model fitted to past sales will predict future revenue without error.
  2. It removes the need to collect new data because past records already contain every answer.
  3. It compresses the whole dataset into summary measures such as the mean and standard deviation.
  4. It draws conclusions about a population parameter from a sample, together with a measure of uncertainty. Correct answer.

Explanation

Inferential statistics generalizes from observed sample data to a broader population or future state, and it always attaches a quantified uncertainty such as a confidence interval or standard error. That uncertainty is essential because the estimate is probabilistic, not a certainty.

Question 2Data Science Foundations and Methodology

A data scientist classifies loan applications as 'default' or 'no default' using labeled historical records. Which machine-learning paradigm does this task belong to?

  1. Supervised learning Correct answer.
  2. Reinforcement learning
  3. Dimensionality reduction
  4. Unsupervised learning

Explanation

When each training example carries a known outcome label (default or no default), the algorithm learns a mapping from inputs to that target, which is supervised learning. Classification with labeled data is its canonical form.

Question 3Data Science Foundations and Methodology

Which activity belongs to the data-understanding phase of the CRISP-DM lifecycle rather than to data preparation?

  1. Splitting the dataset into training and test sets
  2. One-hot encoding categorical features
  3. Profiling variables and assessing data quality issues Correct answer.
  4. Imputing missing values in a numeric column

Explanation

Data understanding focuses on collecting the initial data and describing, exploring, and verifying its quality so that problems are known before modeling. Transformation steps such as imputation, encoding, and splitting belong to later data-preparation work.

Question 4Data Science Foundations and Methodology

A dataset records customer age in years. Which measurement scale does this variable use?

  1. Nominal
  2. Ratio Correct answer.
  3. Ordinal
  4. Interval

Explanation

Age in years has a true zero point and equal intervals, and meaningful ratios can be formed, for example one person being twice as old as another. Those properties define the ratio scale.

Question 5Data Science Foundations and Methodology

Which statement correctly distinguishes a population from a sample in a data science study?

  1. The sample must contain every possible observation to support valid statistical inference.
  2. The population is the entire set of units of interest, while the sample is a subset used for analysis. Correct answer.
  3. The population always equals the sample size when the data are stored in a relational database.
  4. The sample is the entire set of units of interest, while the population is a subset used for analysis.

Explanation

The population is the complete collection of units about which conclusions are wanted, and the sample is the subset actually observed. Inference works precisely because a well-drawn sample can represent a much larger population.

Question 6Data Science Foundations and Methodology

A hospital wants to know whether a new triage protocol shortens waiting time. Which question formulation is the most testable data science question?

  1. Should hospitals always adopt the newest protocols?
  2. By how many minutes does the new triage protocol reduce median waiting time compared with the current protocol? Correct answer.
  3. Why do patients dislike waiting in hospitals?
  4. Is waiting time an interesting topic for data science?

Explanation

A well-posed analytical question names the measurable outcome, the comparison, and the unit of measurement, which makes it verifiable with data. Specifying median waiting time in minutes against the current protocol allows a concrete, falsifiable analysis.

Question 7Data Science Foundations and Methodology

Which task is a canonical example of unsupervised learning?

  1. Segmenting customers into groups using only their purchase behavior, with no predefined group labels Correct answer.
  2. Estimating the probability of churn from historical labels
  3. Predicting house prices from labeled sales records
  4. Classifying emails as spam using a labeled training set

Explanation

Clustering customers by behavioral similarity without predefined labels is unsupervised learning, because the algorithm discovers structure rather than learning from a target. The other options all rely on known outcome labels.

Question 8Data Science Foundations and Methodology

In the CRISP-DM lifecycle, which phase immediately follows data preparation and involves selecting and tuning modeling techniques?

  1. Business understanding
  2. Modeling Correct answer.
  3. Deployment
  4. Data understanding

Explanation

After data preparation produces an analysis-ready dataset, the modeling phase applies candidate algorithms and tunes their parameters. Evaluation then judges the resulting models against business success criteria.

Question 9Data Science Foundations and Methodology

A team reports that a model predicts a binary outcome with 95% accuracy on a dataset where 95% of records belong to the majority class. What is the most important concern to raise?

  1. The accuracy figure may be misleading because a trivial majority-class predictor would score the same. Correct answer.
  2. Accuracy is always the preferred metric for imbalanced classification problems.
  3. The dataset is too large for the model to learn anything meaningful.
  4. The model must be using unsupervised learning because the outcome is binary.

Explanation

When one class dominates, a naive predictor that always outputs the majority label achieves the base rate, so high accuracy can hide poor detection of the minority class. Metrics such as precision, recall, F1, or balanced accuracy reveal whether the model adds value.

Question 10Data Science Foundations and Methodology

A researcher computes a 95% confidence interval for the mean delivery time as 28 to 34 minutes. Which interpretation is correct?

  1. There is a 95% probability that the true population mean lies between 28 and 34 minutes, given the standard frequentist assumptions.
  2. If the study were repeated many times, about 95% of intervals constructed this way would contain the true population mean. Correct answer.
  3. 95% of individual deliveries take between 28 and 34 minutes.
  4. The sample mean is guaranteed to fall outside the interval in 5% of all possible samples.

Explanation

The frequentist confidence interval has a coverage interpretation: across repeated sampling, roughly 95% of intervals built with the same procedure capture the true parameter. It does not describe the distribution of individual observations.

Question 11Data Science Foundations and Methodology

A model is trained and tested on the same rows and reports 0.98 R-squared, but on new data it performs poorly. What is the most likely explanation?

  1. The target variable was measured on a nominal scale.
  2. The model used a supervised paradigm when it should have used reinforcement learning.
  3. The data contain too few features for any model to learn.
  4. The model has overfit because evaluation was not done on held-out data. Correct answer.

Explanation

Evaluating on the training data measures memorization rather than generalization, so an inflated score that collapses on new data is a classic sign of overfitting. A separate validation or test set gives an honest estimate of out-of-sample performance.

Question 12Data Science Foundations and Methodology

Which practice reduces the risk of data leakage when building a predictive pipeline?

  1. Fitting all preprocessing steps only on the training data and then applying them to the test data. Correct answer.
  2. Including the target variable as an additional input feature to improve signal.
  3. Fitting scalers and encoders on the full dataset before splitting into train and test.
  4. Randomly shuffling labels to make the classes more balanced.

Explanation

Data leakage occurs when information from the test set influences training, so preprocessing parameters must be learned from training data only and then applied to held-out data. This keeps the test set a genuine proxy for unseen cases.

Question 13Data Science Foundations and Methodology

A beginner says a p-value of 0.03 proves the null hypothesis is false with 97% certainty. Which correction is most accurate?

  1. A p-value below 0.05 guarantees that the result will replicate in a new sample.
  2. The p-value is the probability of observing data at least as extreme as the sample, assuming the null hypothesis is true. Correct answer.
  3. The p-value measures the size of the effect rather than evidence against the null.
  4. The p-value equals the probability that the null hypothesis is true.

Explanation

A p-value is computed under the assumption that the null hypothesis holds and quantifies how unusual the observed data would be in that world. It is not the probability that the null is true, nor does it measure effect size or guarantee replication.

Question 14Data Science Foundations and Methodology

Which statement best describes the purpose of a data dictionary in a data science project?

  1. It documents each variable's name, meaning, data type, units, and allowed values. Correct answer.
  2. It stores the trained model weights for deployment.
  3. It lists the programming languages supported by the analysis environment.
  4. It records the salaries of the project team members.

Explanation

A data dictionary is metadata that makes a dataset interpretable and auditable by defining fields, types, units, and permissible values. It supports reproducibility and reduces ambiguity when multiple people use the same data.

Question 15Data Science Foundations and Methodology

A survey of 400 randomly selected subscribers finds 62% satisfied, with a margin of error of about 5 percentage points at 95% confidence. What does the margin of error indicate?

  1. The survey instrument has a 5% measurement error on every question.
  2. Exactly 5% of respondents answered dishonestly.
  3. Plausible values for the population satisfaction rate lie roughly within 62% plus or minus 5 points. Correct answer.
  4. The estimate would change by 5 points if the sample size were doubled.

Explanation

The margin of error defines a range around the sample estimate that is likely to contain the true population value at the stated confidence level. It reflects sampling variability, not dishonesty or instrument error.

Question 16Data Science Foundations and Methodology

A dataset of website sessions has a heavily right-skewed distribution of session duration with a few extreme outliers. Which summary is most appropriate for describing typical duration?

  1. The maximum, because it reflects the longest possible session
  2. The median, because it is resistant to extreme values Correct answer.
  3. The mean, because it uses every observation equally
  4. The standard deviation, because it captures spread around the center

Explanation

For skewed data with outliers, the median better represents a typical value because it depends on rank rather than magnitude. The mean is pulled upward by extreme observations and can mislead.

Question 17Data Science Foundations and Methodology

A company wants to predict monthly sales from advertising spend, and the relationship appears roughly linear. Which approach is the most direct first choice?

  1. Principal component analysis on the single predictor
  2. A confusion matrix to compare predicted and actual sales
  3. K-means clustering on the sales values
  4. Simple linear regression with spend as the predictor Correct answer.

Explanation

Predicting a continuous outcome from one continuous predictor with an approximately linear relationship is the textbook setting for simple linear regression. It estimates an intercept and slope that can be interpreted directly.

Question 18Data Science Foundations and Methodology

An analyst splits data into training, validation, and test sets. What is the primary role of the validation set?

  1. To tune hyperparameters and compare candidate models during development Correct answer.
  2. To replace the training set when the dataset is small
  3. To provide the final unbiased estimate of performance after all tuning is complete
  4. To store the labels that the model will predict in production

Explanation

The validation set guides model selection and hyperparameter tuning so that choices are not made on the test set. The test set is reserved for a final, once-only estimate of generalization performance.

Question 19Data Science Foundations and Methodology

A data scientist finds that a customer churn model has 0.85 recall but only 0.40 precision for the churn class. For a retention campaign that contacts predicted churners, what does this trade-off imply?

  1. The model is perfectly calibrated and needs no further adjustment.
  2. Most contacted customers would have churned, but many actual churners are missed.
  3. Most actual churners are captured, but many contacted customers would not have churned. Correct answer.
  4. The model has no false positives and no false negatives.

Explanation

Recall of 0.85 means the model finds most true churners, while precision of 0.40 means only 40% of predicted churners actually churn. The campaign therefore reaches most at-risk customers but wastes outreach on many who would have stayed.

Question 20Data Science Foundations and Methodology

Which sequence correctly orders the first steps of a typical data science workflow when starting from a business request?

  1. Model, deploy, define the problem, collect data
  2. Evaluate results, define the problem, collect data, deploy a model
  3. Collect data, deploy a model, define the problem, evaluate results
  4. Define the problem, collect and prepare data, explore and model, evaluate, communicate results Correct answer.

Explanation

A sound workflow begins by translating the business request into an analytical problem, then gathers and prepares data, explores and models it, evaluates against criteria, and communicates findings. Deployment or communication follows evaluation rather than preceding problem definition.

Question 21Data Science Foundations and Methodology

A team trains five different classifiers and repeatedly evaluates each on the same test set, choosing the one with the best test score. Why is the reported best score potentially optimistic?

  1. Because five models always overfit more than one model regardless of the data.
  2. Because classifiers cannot be compared on a common test set at all.
  3. Because the test set was used for model selection, so it no longer provides an unbiased estimate. Correct answer.
  4. Because the training set must have contained the test rows for the score to be computed.

Explanation

Repeatedly consulting the test set to choose among candidates effectively tunes on it, so the winning score is biased upward. A clean protocol selects models on validation data and touches the test set only once for a final estimate.

Question 22Data Science Foundations and Methodology

A researcher tests 40 separate hypotheses at a significance level of 0.05 and finds 3 significant results. Why should these findings be treated cautiously?

  1. Because a significance level of 0.05 is too strict for any exploratory study.
  2. Because three significant results always indicate that the study was underpowered.
  3. Because a p-value below 0.05 cannot occur when more than one hypothesis is tested.
  4. Because with many tests, the chance of false positives grows unless a multiplicity correction is applied. Correct answer.

Explanation

Each test carries its own false-positive risk, so running many tests inflates the family-wise error rate well beyond 0.05. Corrections such as Bonferroni or Benjamini-Hochberg control this inflation and should be applied before drawing conclusions.

Question 23Data Science Foundations and Methodology

A model uses 'days since last purchase' as a feature, but this value is computed at the time of scoring rather than at the time of the historical event. What problem does this create?

  1. No problem, because recency features are always safe to compute at scoring time.
  2. A nominal-scale violation, because days are numeric but should be categorical.
  3. Underfitting, because time-based features always reduce model complexity.
  4. Target leakage, because future information enters the features and inflates apparent performance. Correct answer.

Explanation

Computing a feature with information available only after the prediction point introduces future information, a form of leakage that makes offline performance look better than it will be in production. Features must reflect only what would be known at prediction time.

Question 24Data Science Foundations and Methodology

An analyst reports that ice cream sales and drowning incidents are strongly correlated across months. Which conclusion is defensible?

  1. The correlation proves that drowning incidents increase ice cream demand.
  2. Eating ice cream causes drowning, so sales should be restricted.
  3. The correlation likely reflects a common seasonal driver such as warm weather, so causal claims are unwarranted. Correct answer.
  4. Correlation coefficients above 0.7 always establish a causal mechanism.

Explanation

Correlation measures association, not causation, and a lurking variable such as temperature can drive both series. Without a controlled design or causal identification strategy, the observed relationship cannot support a causal conclusion.

Question 25Python for Data Science and Programming Fundamentals

In Python, which data type is immutable and can be used as a dictionary key?

  1. tuple Correct answer.
  2. list
  3. dict
  4. set

Explanation

Dictionary keys must be hashable, and hashability requires immutability. A tuple of immutable elements is hashable, so it can serve as a key, whereas mutable containers cannot because their hash would change after insertion.

Question 26Python for Data Science and Programming Fundamentals

What does the expression 7 // 2 evaluate to in Python 3?

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

Explanation

The // operator performs floor division, dividing and then rounding down to the nearest integer. For positive operands 7 // 2 gives 3, discarding the remainder.

Question 27Python for Data Science and Programming Fundamentals

After executing nums = [10, 20, 30, 40], what is the value of nums[1:3]?

  1. [30]
  2. [20, 30, 40]
  3. [20, 30] Correct answer.
  4. [10, 20]

Explanation

Slicing with [start:stop] includes the start index and excludes the stop index. Index 1 holds 20 and index 2 holds 30, so the slice returns [20, 30].

Question 28Python for Data Science and Programming Fundamentals

Which statement correctly creates a pandas DataFrame from a dictionary of equal-length lists?

  1. df = pandas.DataFrame(['a', [1, 2]])
  2. df = DataFrame.from_list({'a': [1, 2]})
  3. df = pandas.DataFrame({'a': [1, 2], 'b': [3, 4]}) Correct answer.
  4. df = pandas.Series({'a': [1, 2]})

Explanation

pandas.DataFrame accepts a dictionary whose keys become column labels and whose list values become column data, provided lengths match. This is the standard constructor pattern for building a DataFrame from column-oriented data.

Question 29Python for Data Science and Programming Fundamentals

What is the primary purpose of a function in a Python data analysis script?

  1. To guarantee that code runs faster than inline code
  2. To convert all variables into global scope
  3. To prevent any variable from being reassigned
  4. To package reusable logic that can be called with different inputs Correct answer.

Explanation

Functions encapsulate a block of logic behind a name and parameters, letting you reuse it with different arguments and avoid duplication. They also create a local scope, which helps organize and isolate intermediate variables.

Question 30Python for Data Science and Programming Fundamentals

Which pandas method returns the number of rows and columns in a DataFrame as a tuple?

  1. df.dtypes
  2. df.columns
  3. df.shape Correct answer.
  4. df.size

Explanation

The shape attribute returns a tuple of the form (rows, columns), which is the quickest way to check dataset dimensions. It is an attribute, so it is accessed without parentheses.

Question 31Python for Data Science and Programming Fundamentals

Which built-in Python structure stores unique elements and does not preserve insertion order guarantees for indexing?

  1. list
  2. string
  3. set Correct answer.
  4. tuple

Explanation

A set stores unique, hashable elements and automatically removes duplicates. It is unordered with respect to indexing, so elements are accessed by membership rather than position.

Question 32Python for Data Science and Programming Fundamentals

What does the expression 'data' * 2 evaluate to?

  1. A TypeError
  2. ['data', 'data']
  3. 'datadata' Correct answer.
  4. 'data data'

Explanation

Multiplying a string by an integer repeats the string that many times and concatenates the copies. Because 2 is an integer, 'data' * 2 yields 'datadata'.

Question 33Python for Data Science and Programming Fundamentals

Given df with a numeric column 'price', which expression returns only the rows where price exceeds 100?

  1. df[df['price'] > 100] Correct answer.
  2. df.query['price'] > 100
  3. df.loc['price'] > 100
  4. df['price' > 100]

Explanation

A boolean Series produced by df['price'] > 100 is used as a mask inside brackets to filter rows. This returns the subset of the DataFrame where the condition is True.

Question 34Python for Data Science and Programming Fundamentals

What is the difference between a Python list and a NumPy array when adding a scalar?

  1. Both behave identically for all scalar additions
  2. A NumPy array broadcasts the scalar element-wise; a list concatenation fails or repeats Correct answer.
  3. A list broadcasts the scalar to each element; an array raises an error
  4. A NumPy array converts the scalar to a string first

Explanation

NumPy uses broadcasting so that adding a scalar applies element-wise across the whole array. A list does not support element-wise arithmetic with a scalar, so the operation raises a TypeError.

Question 35Python for Data Science and Programming Fundamentals

Which statement about the difference between .loc and .iloc in pandas is correct?

  1. .loc uses labels; .iloc uses integer positions Correct answer.
  2. .iloc only works on Series, not DataFrames
  3. .loc uses integer positions; .iloc uses labels
  4. Both always use integer positions

Explanation

.loc selects by label, including label-based slices that are inclusive of the endpoint. .iloc selects by zero-based integer position, with slices excluding the stop position.

Question 36Python for Data Science and Programming Fundamentals

What does the following code print? def add_item(item, basket=[]): basket.append(item) return basket print(add_item('a')) print(add_item('b'))

  1. An error on the second call
  2. ['a'] then ['a', 'b'] Correct answer.
  3. ['a'] then ['b']
  4. ['a', 'b'] then ['a', 'b']

Explanation

Default argument values are evaluated once when the function is defined, so the same mutable list is reused across calls. The first call appends 'a' and the second appends 'b' to that same list, producing ['a'] and then ['a', 'b'].

Question 37Python for Data Science and Programming Fundamentals

Which pandas method is best for computing the mean of each numeric column while ignoring NaN values by default?

  1. df.mean() Correct answer.
  2. df.count()
  3. df.sum()
  4. df.describe()

Explanation

df.mean() computes the mean per numeric column and skips NaN values by default via skipna=True. It returns a Series indexed by column name.

Question 38Python for Data Science and Programming Fundamentals

What is the result of the list comprehension [x**2 for x in range(4) if x % 2 == 0]?

  1. [0, 4] Correct answer.
  2. [1, 9]
  3. [0, 1, 4, 9]
  4. [0, 2, 4]

Explanation

The condition keeps only even values of x from range(4), which are 0 and 2. Squaring each yields 0 and 4, so the list is [0, 4].

Question 39Python for Data Science and Programming Fundamentals

In pandas, what does df.groupby('category')['sales'].mean() return?

  1. A boolean mask of sales values
  2. A Series of mean sales per category Correct answer.
  3. A DataFrame with all original rows
  4. A single float of the overall mean

Explanation

groupby splits the data by category, the column selection isolates sales, and mean aggregates within each group. The result is a Series indexed by the distinct category values.

Question 40Python for Data Science and Programming Fundamentals

Which statement correctly describes how to handle a missing value in pandas using fillna?

  1. df.fillna(0) returns a new object unless inplace=True is set Correct answer.
  2. fillna only works on string columns
  3. df.fillna(0) permanently modifies df in place by default
  4. fillna deletes rows containing NaN

Explanation

Most pandas methods, including fillna, return a new object by default and leave the original unchanged. Passing inplace=True or reassigning the result is needed to persist the fill.

Question 41Python for Data Science and Programming Fundamentals

What is the output of print(type(3 / 1)) in Python 3?

  1. <class 'str'>
  2. <class 'int'>
  3. <class 'float'> Correct answer.
  4. <class 'decimal.Decimal'>

Explanation

In Python 3, the single slash operator performs true division and always returns a float, even when the result is a whole number. So 3 / 1 yields 3.0 of type float.

Question 42Python for Data Science and Programming Fundamentals

Why is a NumPy array generally more memory-efficient than a Python list of the same numbers?

  1. It stores elements as contiguous values of a single dtype Correct answer.
  2. It deletes elements that are zero
  3. It stores each element as a full Python object
  4. It automatically compresses duplicate values

Explanation

A NumPy array holds a contiguous block of memory with a fixed dtype, avoiding the per-element object overhead of a Python list. This compact layout also enables vectorized operations.

Question 43Python for Data Science and Programming Fundamentals

What does the following code produce? x = 5 def f(): x = 10 f() print(x)

  1. An UnboundLocalError
  2. None
  3. 5 Correct answer.
  4. 10

Explanation

Assigning to x inside f creates a new local variable that shadows the global one, so the global x is untouched. After the call, the module-level x remains 5.

Question 44Python for Data Science and Programming Fundamentals

Which pandas operation reshapes a DataFrame from wide to long format by turning columns into rows?

  1. df.transpose() only
  2. df.merge(df)
  3. df.pivot()
  4. pd.melt(df) Correct answer.

Explanation

pd.melt unpivots a wide DataFrame, turning identifier columns into rows and value columns into a variable/value pair. It is the standard wide-to-long reshaping tool.

Question 45Python for Data Science and Programming Fundamentals

Consider a DataFrame df where column 'a' contains [1, 2, 3] and column 'b' contains [4, 5, 6]. What does df.apply(lambda row: row['a'] + row['b'], axis=1) return?

  1. A single integer 21
  2. A Series [5, 5, 5]
  3. A Series [5, 7, 9] Correct answer.
  4. A DataFrame of two columns

Explanation

With axis=1, apply passes each row as a Series to the function, and the lambda sums the row's 'a' and 'b' values. The result is a Series aligned to the original index with values 5, 7, and 9.

Question 46Python for Data Science and Programming Fundamentals

What is the result of the following expression? import numpy as np a = np.array([1, 2, 3]) b = np.array([[10], [20]]) print((a + b).shape)

  1. (2, 3) Correct answer.
  2. (3,)
  3. (2,)
  4. A ValueError is raised

Explanation

Broadcasting aligns shapes from the right: a has shape (3,) and b has shape (2, 1). The size-1 axis of b stretches to 3, and a stretches to 2 rows, producing shape (2, 3).

Question 47Python for Data Science and Programming Fundamentals

A DataFrame has NaN values in column 'score'. Which approach computes the median of the non-null scores while leaving df unchanged?

  1. df['score'].isna().median()
  2. df['score'].dropna().median() Correct answer.
  3. df['score'].fillna(0).median()
  4. df['score'].median(dropna=False)

Explanation

dropna removes missing values and returns a new Series, so the median is computed over only valid scores and df is untouched. median already skips NaN, but dropna makes the intent explicit without altering the frame.

Question 48Python for Data Science and Programming Fundamentals

What does the following code print? d = {'a': 1, 'b': 2} for k in d: d[k] = d[k] * 10 print(sum(d.values()))

  1. 33
  2. 3
  3. A RuntimeError is raised
  4. 30 Correct answer.

Explanation

Iterating over a dict yields its keys, and modifying the value for an existing key does not change the dict's size, so no error is raised. The values become 10 and 20, and their sum is 30.

Question 49Python for Data Science and Programming Fundamentals

Which expression produces a Series containing the correlation of column 'x' with every other numeric column in df?

  1. df.corrwith(df['x'])
  2. df['x'].corr()
  3. df.corr()['x'] Correct answer.
  4. df['x'].cov(df)

Explanation

df.corr() returns a square correlation matrix indexed and columned by numeric variables, and selecting ['x'] extracts that variable's row as a Series. This gives the correlation of x with each other numeric column.

Question 50Python for Data Science and Programming Fundamentals

In a Python for Data Science workflow, which statement correctly describes the role of the `if __name__ == "__main__":` block?

  1. It forces the interpreter to recompile the module every time it is imported.
  2. It ensures the code inside runs only when the script is executed directly, not when imported as a module. Correct answer.
  3. It makes all functions defined in the script globally available without an import statement.
  4. It defines the entry point for Jupyter notebook cells and is required for any cell to execute.

Explanation

The special variable __name__ is set to "__main__" only when the file is run as the top-level script; on import it holds the module name, so the guarded block is skipped. This pattern lets a module expose reusable functions while still offering a command-line entry point.