← All articlesData Science

A/B Testing in Python: A Step-by-Step Guide with a Real Checkout Experiment

By Skillancy Editorial Team · 30 November 2026 · 26 min read

Reviewed by Rishav Kumar, Principal Data Analyst, Walmart Global Tech

Skillancy cover: A/B Testing in Python, step by step with sample size, SRM, z-test, guardrails, peeking and novelty. A one-tap UPI checkout test on 42,000 simulated users lifted conversion by 2.5 points and revenue per user by 8.9%, and daily peeking produced false wins 22.7% of the time

A/B testing is a controlled experiment in which users are randomly split into two groups. One group sees the current version (A, the control), the other sees a change (B, the treatment), and you compare a pre-chosen metric to decide whether the change caused an improvement. It's how product, growth and analytics teams at Indian apps decide whether a new checkout, a new price display or a new recommendation actually works, instead of arguing from opinions. This guide runs a complete A/B test in Python on a realistic checkout experiment for a food delivery app. It covers the hypothesis, sample size and power, A/A tests, a sample ratio mismatch check, the z-test and confidence interval, guardrail metrics, the peeking trap, the novelty effect, segments and the final decision. Every number shown comes from running the code, so you can reproduce it in Google Colab.

QuestionShort answer
What is A/B testing in simple words?Randomly show two versions to two groups of users and measure which one performs better on one metric
Which statistical test is used for A/B testing?A two-proportion z-test (or chi-square test) for rates such as conversion; Welch's t-test or Mann-Whitney for values such as order value
How do I calculate the sample size?From the baseline rate, the minimum detectable effect, significance level (usually 5%) and power (usually 80%). In Python: NormalIndPower().solve_power()
How long should an A/B test run?Until it reaches the planned sample size, rounded up to full weeks so every weekday is covered. Usually at least 1 to 2 weeks
What is the peeking problem?Stopping as soon as p < 0.05 while checking repeatedly. In our simulation it raised false positives from 5% to 22.7%
What is sample ratio mismatch?When the group sizes differ from the planned split more than chance allows. It signals a bug, and the results can't be trusted
A/B testing vs hypothesis testing?An A/B test is an experiment design; hypothesis testing is the statistics used to analyse it
Data note: the experiment in this post is simulated by the code below, with a known true effect, so you can see whether each method finds the truth. It's modelled on a food delivery checkout but isn't any company's real data. The workflow and the code are what you'd use on real experiment logs.

New to the statistics? The free Python lessons on hypothesis testing, sampling and confidence intervals and descriptive statistics cover the building blocks in short, runnable examples.

What is A/B testing?

An A/B test (also called a split test, a bucket test or an online controlled experiment) answers one causal question: if we ship this change, does the metric we care about improve? Users are assigned at random to the control or the treatment. Because the assignment is random, the two groups are alike on average in everything else (city, phone, mood, payday), so a difference in the metric can be credited to the change.

That's what makes A/B tests stronger than before-and-after comparisons or dashboards. As we showed in correlation vs causation, comparing customers who chose something with those who didn't can overstate an effect several times over. Randomisation removes that self-selection.

Where Indian companies use A/B tests

TeamTypical experimentPrimary metric
Food delivery, quick commerceNew checkout flow, delivery-fee display, coupon placementCheckout conversion, orders per user
E-commerceProduct page layout, "Buy now" button, COD vs prepaid nudgesAdd-to-cart rate, conversion, return rate
Fintech and paymentsUPI autopay prompt, onboarding steps, KYC flowActivation rate, completed KYC
Edtech and mediaFree-trial length, paywall copy, push notification timingTrial-to-paid conversion, retention
MarketingEmail subject lines, ad creatives, landing pagesOpen rate, click-through rate, cost per lead
AI productsPrompt or model version, ranking algorithmTask success, user rating, cost per answer

A/B testing vs hypothesis testing vs other experiments

TermWhat it is
A/B testAn experiment: two versions, random assignment, one primary metric
Hypothesis testingThe statistics (null hypothesis, test, p-value) used to analyse the A/B test
A/A testBoth groups get the same version. Used to check the setup: about 5% of A/A tests should look "significant" by chance
A/B/n testMore than two versions at once. Needs more users and a multiple-testing correction
Multivariate testSeveral elements changed in combination (button × headline × image) to find the best mix and interactions
Canary or staged rolloutReleasing to a small share of users to catch bugs. It's about safety, not measuring impact

The experiment: a one-tap UPI checkout

A food delivery app wants to test a new checkout that pre-selects the user's last UPI app and places the order in one tap, instead of the current 3-screen payment flow.

  • Unit: a user who reaches the checkout page, randomly assigned 50/50 by user ID (so the same person always sees the same version).
  • Baseline: 22% of checkout users place an order.
  • Traffic: about 3,000 users reach checkout each day.

A/B testing workflow: design the hypothesis and metrics, calculate sample size, run an A/A test, launch and check sample ratio mismatch, analyse with a z-test and confidence interval, check guardrails, novelty and peeking, then decide

Step 1: Write the hypothesis and pick metrics

Write these down before any data arrives. Changing them afterwards is how teams fool themselves.

ItemFor this test
HypothesisOne-tap UPI checkout removes payment friction, so more checkout users place an order
Null hypothesis (H0)Conversion is the same in control and treatment
Alternative (H1)Conversion is different (two-sided test)
Primary metricCheckout-to-order conversion rate per user
Guardrail metricsAverage order value (₹), payment failure rate, revenue per checkout user
Minimum detectable effect (MDE)+1.5 percentage points (22% → 23.5%), the smallest lift worth the engineering cost
Significance level (α) and power5% and 80%
Decision ruleShip if conversion rises significantly and no guardrail is significantly harmed beyond what revenue per user can absorb

Why a two-sided test? A new checkout can also make things worse. A one-sided test would never flag that.

Why guardrails? A change can win on its own metric while hurting the business elsewhere. One-tap payment could raise orders but shrink baskets, because users skip the "add more" screen. Guardrails catch that.

Step 2: Calculate the sample size and duration

The sample size depends on four inputs: the baseline rate, the MDE, α and power. Smaller effects need many more users. Here it is with the textbook formula and with statsmodels:

import numpy as np
import pandas as pd
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
from scipy.stats import norm

baseline = 0.22          # current checkout-to-order conversion
mde = 0.015              # smallest lift worth detecting: +1.5 percentage points
alpha, power = 0.05, 0.80

# By hand: the classic two-proportion formula
p1, p2 = baseline, baseline + mde
p_bar = (p1 + p2) / 2
z_a, z_b = norm.ppf(1 - alpha / 2), norm.ppf(power)
n_hand = ((z_a * np.sqrt(2 * p_bar * (1 - p_bar)) + z_b * np.sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2) / mde ** 2
print(f"Formula: {np.ceil(n_hand):,.0f} users per group")

# With statsmodels (Cohen's h effect size)
h = proportion_effectsize(p2, p1)
n_sm = NormalIndPower().solve_power(effect_size=h, alpha=alpha, power=power, ratio=1.0, alternative="two-sided")
print(f"statsmodels: {np.ceil(n_sm):,.0f} users per group (Cohen's h = {h:.4f})")

daily_users = 3_000      # users reaching checkout per day, split 50/50
days = np.ceil(2 * n_sm / daily_users)
print(f"At {daily_users:,} checkout users a day: {days:.0f} days -> round up to {int(np.ceil(days / 7) * 7)} days (full weeks)")

rows = []
for m in [0.005, 0.01, 0.015, 0.02, 0.03]:
    n = NormalIndPower().solve_power(proportion_effectsize(baseline + m, baseline), alpha=alpha, power=power)
    rows.append({"mde_pp": m * 100, "relative_lift": f"{m / baseline:.1%}", "users_per_group": int(np.ceil(n)),
                 "days_at_3000_a_day": int(np.ceil(2 * n / daily_users))})
print(pd.DataFrame(rows).to_string(index=False))

Output:

Formula: 12,261 users per group
statsmodels: 12,259 users per group (Cohen's h = 0.0358)
At 3,000 checkout users a day: 9 days -> round up to 14 days (full weeks)
 mde_pp relative_lift  users_per_group  days_at_3000_a_day
    0.5          2.3%           108622                  73
    1.0          4.5%            27370                  19
    1.5          6.8%            12259                   9
    2.0          9.1%             6948                   5
    3.0         13.6%             3133                   3

Users needed per group against the minimum detectable effect at a 22% baseline: 12,259 per group for +1.5 points, rising steeply below +1 point to over 100,000 for +0.5 points

How to read it:

  • The formula and statsmodels agree (12,261 vs 12,259; the tiny gap is two slightly different approximations). You need about 12,300 users per group, about 24,500 in total.
  • At 3,000 users a day that takes 9 days. Round up to 14 days: ordering behaviour on Saturday night is different from Tuesday afternoon, so cover full weeks. Our test runs 14 days and collects 42,000 users, more than planned, which also gives extra power.
  • Halving the MDE roughly quadruples the sample. Detecting +0.5 points would need 108,622 users per group and 73 days. If you can't wait that long, you can't reliably detect effects that small. Decide that before the test, not after.
  • Power 80% means that if the true lift really is +1.5 points, the test detects it 80% of the time. A test with too few users usually ends "not significant" even when the change works.

Step 3: Run A/A tests to understand the p-value

Before trusting any result, see what "significant" means when there's no real difference. This simulates 2,000 A/A tests where both groups have exactly the same 22% conversion:

from statsmodels.stats.proportion import proportions_ztest

rng = np.random.default_rng(7)
n_per = 14_000
false_pos = 0
for _ in range(2_000):
    a = rng.binomial(n_per, baseline)
    b = rng.binomial(n_per, baseline)          # same true rate: any "win" is luck
    _, p = proportions_ztest([a, b], [n_per, n_per])
    false_pos += p < 0.05
print(f"A/A tests with p < 0.05: {false_pos} of 2,000 ({false_pos / 2000:.1%})")
A/A tests with p < 0.05: 93 of 2,000 (4.7%)

About 5% of A/A tests look "significant" purely by chance. That's what α = 0.05 means: if there is no effect, you'll still see p < 0.05 about 1 time in 20. A p-value isn't the probability that the treatment works. It's how surprising the data would be if there were no difference.

Real platforms run live A/A tests for the same reason: if far more than 5% of them come out significant, the randomisation or logging is broken.

Step 4: The experiment data

Now the real experiment: 14 days, 42,000 checkout users. The simulation has a true lift of +1.8 points, plus a temporary novelty bump in the first few days, a slightly smaller average order value in the treatment, and a tiny rise in payment failures.

rng = np.random.default_rng(42)
N = 42_000                                       # 14 days x 3,000 users
df = pd.DataFrame({
    "user_id": [f"U{i:06d}" for i in range(N)],
    "group": rng.choice(["control", "treatment"], N),
    "day": rng.integers(1, 15, N),
    "platform": rng.choice(["Android", "iOS"], N, p=[0.78, 0.22]),
    "city_tier": rng.choice(["Tier 1", "Tier 2"], N, p=[0.6, 0.4]),
})
is_t = (df["group"] == "treatment").to_numpy()
rate = (baseline
        + np.where(df["platform"] == "iOS", 0.04, 0.0)
        + np.where(df["city_tier"] == "Tier 2", -0.03, 0.0)
        + is_t * 0.018                                          # true lift: +1.8 points
        + is_t * 0.03 * np.exp(-(df["day"].to_numpy() - 1) / 2))  # novelty bump in the first days
df["converted"] = (rng.random(N) < rate).astype(int)
aov = rng.lognormal(np.log(340), 0.45, N) * np.where(is_t, 0.985, 1.0)   # rupees
df["order_value"] = np.where(df["converted"] == 1, aov.round(), np.nan)
pay_fail = rng.random(N) < np.where(is_t, 0.034, 0.031)
df["payment_failed"] = np.where(df["converted"] == 1, pay_fail.astype(int), np.nan)

import os
os.makedirs("data", exist_ok=True)
os.makedirs("charts", exist_ok=True)
df.to_csv("data/checkout_experiment.csv", index=False)
print(df.shape)
print(df.head(4).to_string(index=False))
(42000, 8)
user_id     group  day platform city_tier  converted  order_value  payment_failed
U000000   control    6  Android    Tier 1          1        170.0             0.0
U000001 treatment    6  Android    Tier 1          0          NaN             NaN
U000002 treatment   14  Android    Tier 2          0          NaN             NaN
U000003   control   11  Android    Tier 1          0          NaN             NaN

One row per user: which group they were in, the day they arrived, their platform and city tier, whether they ordered, and (for orders) the order value in rupees and whether the payment failed.

Step 5: Check for sample ratio mismatch first

Before looking at conversion, check that the split is what you planned. With a 50/50 design, the group sizes should differ only by chance. A sample ratio mismatch (SRM) test is a chi-square goodness-of-fit test on the counts:

from scipy.stats import chisquare

counts = df["group"].value_counts().sort_index()
print(counts.to_string())
stat, p_srm = chisquare(counts, f_exp=[len(df) / 2] * 2)
print(f"SRM chi-square p = {p_srm:.3f}")

# A broken run: the new checkout crashed on old iOS versions and 1,000 treatment users were never logged
broken = df.drop(df[(df["group"] == "treatment") & (df["platform"] == "iOS")].sample(1_000, random_state=1).index)
bc = broken["group"].value_counts().sort_index()
stat_b, p_srm_b = chisquare(bc, f_exp=[len(broken) / 2] * 2)
print(bc.to_string())
print(f"Broken run SRM p = {p_srm_b:.2e}")
group
control      20932
treatment    21068
SRM chi-square p = 0.507
group
control      20932
treatment    20068
Broken run SRM p = 1.98e-05
  • Healthy run: 20,932 vs 21,068 users, p = 0.507. That's a normal random wobble, so go ahead.
  • Broken run: suppose the new checkout crashed on older iOS versions and those users were never logged. Treatment drops to 20,068 and the SRM p-value is 0.00002. Stop here. The missing users are not random (they're iOS users, who convert more), so any conversion comparison is biased in an unknown direction.

A common rule is to treat SRM p < 0.001 as a failed experiment. Typical causes: crashes or slow loading in one variant, bots, redirects that lose users, or assignment logged at a different point in each variant. Fix the bug and rerun; don't "adjust" the result.

Step 6: Analyse the primary metric

Compare conversion with a two-proportion z-test, and report the confidence interval for the difference, not just the p-value:

from statsmodels.stats.proportion import confint_proportions_2indep

summary = df.groupby("group")["converted"].agg(users="size", orders="sum", rate="mean")
print(summary.round(4).to_string())
orders = summary["orders"].to_numpy()[::-1]       # treatment first
users = summary["users"].to_numpy()[::-1]
z, p_val = proportions_ztest(orders, users)
lo, hi = confint_proportions_2indep(orders[0], users[0], orders[1], users[1], compare="diff")
diff = orders[0] / users[0] - orders[1] / users[1]
print(f"Difference: {diff * 100:+.2f} points ({diff / (orders[1] / users[1]):+.1%} relative)")
print(f"z = {z:.2f}, p = {p_val:.2g}, 95% CI for the difference: [{lo * 100:+.2f}, {hi * 100:+.2f}] points")

# The same question with a chi-square test on the 2x2 table
from scipy.stats import chi2_contingency
table = pd.crosstab(df["group"], df["converted"])
chi2, p_chi, _, _ = chi2_contingency(table, correction=False)
print(f"Chi-square p = {p_chi:.2g} (same as z-test: z^2 = {z ** 2:.2f}, chi2 = {chi2:.2f})")
           users  orders    rate
group
control    20932    4540  0.2169
treatment  21068    5101  0.2421
Difference: +2.52 points (+11.6% relative)
z = 6.15, p = 7.9e-10, 95% CI for the difference: [+1.72, +3.33] points
Chi-square p = 7.9e-10 (same as z-test: z^2 = 37.79, chi2 = 37.79)

How to report this result:

  • Effect: conversion rose from 21.69% to 24.21%, +2.52 percentage points, or +11.6% relative. Say which one you mean: "+2.5 points" and "+11.6%" describe the same change, and mixing them up is a classic presentation mistake.
  • Uncertainty: the 95% confidence interval is +1.72 to +3.33 points. The whole interval is above zero and above the +1.5-point MDE, so the lift is both statistically significant and large enough to matter.
  • Evidence: p = 7.9 × 10⁻¹⁰. If the new checkout made no difference, a gap this large would almost never happen by chance.
  • Same answer, two tests: for a 2×2 table, the chi-square test without continuity correction is the z-test squared (z² = χ² = 37.79). Use whichever your team knows.

The true lift in the simulation is +1.8 points, so +2.52 is an overestimate, and the interval suggests why that's possible. Step 9 shows the main cause.

Step 7: Check the guardrail metrics

A winning primary metric isn't enough. Check what else moved:

from scipy.stats import ttest_ind, mannwhitneyu

orders_df = df[df["converted"] == 1]
c_aov = orders_df.loc[orders_df["group"] == "control", "order_value"]
t_aov = orders_df.loc[orders_df["group"] == "treatment", "order_value"]
print(f"Average order value: control Rs {c_aov.mean():.0f}, treatment Rs {t_aov.mean():.0f} "
      f"({t_aov.mean() / c_aov.mean() - 1:+.1%})")
print(f"Welch t-test p = {ttest_ind(t_aov, c_aov, equal_var=False).pvalue:.3f}, "
      f"Mann-Whitney p = {mannwhitneyu(t_aov, c_aov).pvalue:.3f}")
fails = orders_df.groupby("group")["payment_failed"].agg(["sum", "size", "mean"])
print(fails.round(4).to_string())
_, p_fail = proportions_ztest(fails["sum"].to_numpy()[::-1], fails["size"].to_numpy()[::-1])
print(f"Payment failure difference p = {p_fail:.3f}")
rev = df.assign(rev=df["order_value"].fillna(0)).groupby("group")["rev"].mean()
print(f"Revenue per checkout user: control Rs {rev['control']:.1f}, treatment Rs {rev['treatment']:.1f} "
      f"({rev['treatment'] / rev['control'] - 1:+.1%})")
Average order value: control Rs 378, treatment Rs 369 (-2.5%)
Welch t-test p = 0.010, Mann-Whitney p = 0.025
             sum  size    mean
group
control    144.0  4540  0.0317
treatment  163.0  5101  0.0320
Payment failure difference p = 0.947
Revenue per checkout user: control Rs 82.0, treatment Rs 89.3 (+8.9%)
  • Average order value fell 2.5% (₹378 to ₹369), and that's significant (Welch p = 0.010). Order values are right-skewed, so we also ran the Mann-Whitney test, which doesn't assume a normal distribution; it agrees (p = 0.025). One-tap checkout seems to cut the moment where users add one more item.
  • Payment failures didn't change (3.17% vs 3.20%, p = 0.947). The new flow isn't breaking payments.
  • Revenue per checkout user rose 8.9% (₹82.0 to ₹89.3), because the extra orders more than make up for the smaller baskets.

That's a real trade-off, and it's the kind of nuance interviewers look for. The honest recommendation is to ship, and to test an "add a dessert?" prompt inside the one-tap flow to win back basket size.

Note that the average order value is measured only on users who ordered, and the treatment converted more users. Those extra, marginal buyers may naturally place smaller orders, so part of the drop could be a mix effect rather than the checkout shrinking anyone's basket. Revenue per checkout user, which includes everyone, avoids that problem and is the safer number for the decision.

Step 8: The peeking trap

The most common way A/B tests go wrong isn't the maths. It's peeking: checking the dashboard every day and stopping as soon as p < 0.05. This simulates 2,000 A/A tests (no real effect) checked daily for 14 days:

rng = np.random.default_rng(11)
sims, daily = 2_000, 1_500                       # per group per day, A/A (no real effect)
stopped_early = 0
first_stop = []
for _ in range(sims):
    a = rng.binomial(daily, baseline, 14).cumsum()
    b = rng.binomial(daily, baseline, 14).cumsum()
    n = daily * np.arange(1, 15)
    for d in range(14):
        _, p = proportions_ztest([a[d], b[d]], [n[d], n[d]])
        if p < 0.05:
            stopped_early += 1
            first_stop.append(d + 1)
            break
_, p_end = zip(*[proportions_ztest([rng.binomial(daily * 14, baseline), rng.binomial(daily * 14, baseline)],
                                   [daily * 14] * 2) for _ in range(sims)])
print(f"Check once on day 14: {np.mean(np.array(p_end) < 0.05):.1%} false positives")
print(f"Check every day, stop at first p < 0.05: {stopped_early / sims:.1%} false positives")
print("Day of the false 'win':", pd.Series(first_stop).value_counts().sort_index().to_dict())
Check once on day 14: 5.5% false positives
Check every day, stop at first p < 0.05: 22.7% false positives
Day of the false 'win': {1: 103, 2: 81, 3: 46, 4: 25, 5: 33, 6: 36, 7: 26, 8: 16, 9: 19, 10: 12, 11: 18, 12: 13, 13: 13, 14: 12}

Chance of a false winner in an A/A test rises with the number of looks: 5% with one look at the end, about 13% with 4 looks, about 19% with 8 and about 23% with daily looks over 14 days

Checking once at the planned end keeps false positives near the promised 5%. Checking daily and stopping at the first "significant" result raises them to 22.7%, more than four times higher. Most false wins appear in the first few days, when samples are small and noisy: 103 of them on day 1 alone.

How to avoid it:

  • Fix the sample size and end date in advance, and decide only at the end. Looking at dashboards for bugs is fine; deciding early isn't.
  • If you must decide early, use a sequential method designed for repeated looks, such as group-sequential boundaries (alpha spending) or always-valid p-values. Many experimentation platforms offer these.
  • Don't extend a test just because it's "almost significant". That's peeking in reverse.

Step 9: Watch for the novelty effect

Users sometimes react to a change simply because it's new: they click the shiny button, then go back to old habits. Plot the lift by day:

by_day = df.pivot_table(index="day", columns="group", values="converted", aggfunc="mean")
by_day["lift_pp"] = (by_day["treatment"] - by_day["control"]) * 100
print(by_day.round(3).to_string())
first, rest = by_day.loc[1:3, "lift_pp"].mean(), by_day.loc[4:, "lift_pp"].mean()
print(f"Average lift days 1-3: {first:+.2f} points; days 4-14: {rest:+.2f} points")
late = df[df["day"] >= 4].groupby("group")["converted"].agg(["sum", "size"])
_, p_late = proportions_ztest(late["sum"].to_numpy()[::-1], late["size"].to_numpy()[::-1])
lo2, hi2 = confint_proportions_2indep(late.loc["treatment", "sum"], late.loc["treatment", "size"],
                                      late.loc["control", "sum"], late.loc["control", "size"], compare="diff")
print(f"Days 4-14 only: p = {p_late:.2g}, 95% CI [{lo2 * 100:+.2f}, {hi2 * 100:+.2f}] points")
group  control  treatment  lift_pp
day
1        0.237      0.271    3.432
2        0.221      0.259    3.778
3        0.206      0.244    3.789
4        0.208      0.243    3.508
5        0.225      0.243    1.808
...
14       0.205      0.231    2.678
Average lift days 1-3: +3.67 points; days 4-14: +2.21 points
Days 4-14 only: p = 1.4e-06, 95% CI [+1.32, +3.12] points

Daily lift in conversion: days 1 to 3 show about +3.4 to +3.8 points, later days vary between +1.1 and +3.5, averaging +2.2 points against +2.5 for the whole test

The first 3 days averaged +3.67 points; days 4 to 14 averaged +2.21 points. The whole-test estimate (+2.52) is pulled up by the novelty days. The settled lift is still clearly positive (95% CI +1.32 to +3.12, p = 1.4 × 10⁻⁶), so the decision doesn't change, but the forecast for the business should use about +2.2 points, not +2.5.

Single days are noisy (day 6 shows +1.1, day 10 +3.1), so don't read meaning into one day. Look for a trend over several days. The opposite pattern also exists: a change aversion effect, where users dislike a change at first and the lift grows over time. Both are reasons to run full weeks and look at the trend before deciding.

Step 10: Segments and the multiple-testing tax

After a win, everyone asks "did it work for iOS? For tier-2 cities?" Segments are useful for learning, but every extra test is another chance of a false positive:

seg_rows = []
for col in ["platform", "city_tier"]:
    for val, g in df.groupby(col):
        s = g.groupby("group")["converted"].agg(["sum", "size"])
        _, p = proportions_ztest(s["sum"].to_numpy()[::-1], s["size"].to_numpy()[::-1])
        r = s["sum"] / s["size"]
        seg_rows.append({"segment": f"{col}={val}", "control": r["control"], "treatment": r["treatment"],
                         "lift_pp": (r["treatment"] - r["control"]) * 100, "p": p})
seg = pd.DataFrame(seg_rows)
seg["p_bonferroni"] = (seg["p"] * len(seg)).clip(upper=1)
print(seg.round(4).to_string(index=False))

rng = np.random.default_rng(3)
hits = 0
for _ in range(1_000):
    ps = [proportions_ztest(rng.binomial(2_000, baseline, 2), [2_000, 2_000])[1] for _ in range(20)]
    hits += min(ps) < 0.05
print(f"A/A test sliced into 20 segments: at least one 'significant' segment in {hits / 10:.1f}% of runs")
         segment  control  treatment  lift_pp      p  p_bonferroni
platform=Android   0.2099     0.2332   2.3375 0.0000        0.0000
    platform=iOS   0.2418     0.2744   3.2689 0.0004        0.0014
city_tier=Tier 1   0.2305     0.2545   2.3926 0.0000        0.0000
city_tier=Tier 2   0.1965     0.2234   2.6881 0.0000        0.0001
A/A test sliced into 20 segments: at least one 'significant' segment in 66.2% of runs
  • In this experiment the lift holds in every segment, even after a Bonferroni correction (multiply each p-value by the number of tests). The iOS lift looks larger (+3.3 vs +2.3 points), but the iOS sample is small; in the simulation the true lift is the same on both platforms.
  • The second line is the warning: slice an A/A test into 20 segments and at least one segment looks "significant" in 66.2% of runs. If you search enough segments you'll always find a "winner".
  • Rule: name the 2 or 3 segments you care about before the test, correct for multiple testing, and treat anything else as a hypothesis for the next experiment.

Step 11: Make the decision and write it up

A one-page experiment summary that a product manager can read in two minutes:

SectionOne-tap UPI checkout
DecisionShip to 100%
Primary metricConversion 21.69% → 24.21%, +2.52 points (95% CI +1.72 to +3.33), p < 0.001
Expected long-run liftAbout +2.2 points after the novelty period (95% CI +1.32 to +3.12)
GuardrailsAverage order value −2.5% (significant); payment failures unchanged; revenue per checkout user +8.9%
Data quality14 full days, 42,000 users, SRM p = 0.507 (healthy)
CaveatsEffect was inflated in the first 3 days; segment results all positive but not pre-registered beyond platform and city tier
Next experimentAdd an "add a dessert?" prompt inside the one-tap flow to recover basket size

Keep a holdback if you can: leave 5% of users on the old checkout for a few weeks after launch to confirm the long-run effect.

Common A/B testing mistakes

MistakeWhat goes wrongFix
No sample size calculationTest ends "not significant" even when the change worksCalculate users needed from baseline, MDE, α and power first
Peeking and stopping earlyFalse positives rise from 5% to 22.7% (our simulation)Fixed end date, or a sequential method
Ignoring SRMBiased results from a hidden bugChi-square check on group sizes before analysis
Reporting only the p-valueNo sense of how big the effect isReport the effect and its confidence interval
Mixing points and percent"+2.5%" when you mean +2.5 points (+11.6%)Always label absolute vs relative
No guardrail metricsWinning on conversion while losing revenuePre-define 2 to 4 guardrails
Running less than a weekMissing weekday and weekend behaviour, noveltyRun full weeks
Fishing in segments"It works for iOS users in Pune!" by chancePre-register segments, correct for multiple tests
Randomising by session instead of userThe same person sees both versionsAssign by a stable user ID
Network effects ignoredIn two-sided markets (riders, sellers), groups affect each otherCluster or switchback designs

A/B testing interview questions

These come up in data analyst, data scientist and product analyst interviews in India. Each answer uses this experiment.

1. How do you decide the sample size for an A/B test? "From the baseline rate (22%), the minimum detectable effect (+1.5 points), α (5%) and power (80%). That gives about 12,300 users per group. Then I convert it to days of traffic and round up to full weeks."

2. What does a p-value of 0.03 mean? "If there were no real difference, data at least this extreme would appear about 3% of the time. It isn't the probability that the treatment works."

3. The test is significant on day 3. Can we stop? "No. Stopping at the first significant result inflates false positives. In a simulation, daily peeking raised them from 5% to 22.7%. We stop at the planned sample size, unless we designed a sequential test."

4. What is sample ratio mismatch? "A gap between the planned and actual split larger than chance allows, tested with chi-square. It usually means a bug, such as a crash in one variant, and the results can't be trusted."

5. Conversion went up but average order value went down. What do you recommend? "Look at a metric that combines both, like revenue per user. Here it rose 8.9%, so I'd ship and test a fix for basket size."

6. Statistical significance vs practical significance? "Significance says the effect is probably not zero. Practical significance asks whether it's big enough to matter. I compare the confidence interval with the minimum effect worth shipping."

7. What is the novelty effect, and how do you handle it? "Users react to something new and then settle. I plot the lift by day and estimate the effect after the first few days. Here it fell from +3.7 to +2.2 points."

8. When can't you run an A/B test? "When randomising is impossible or unethical, when traffic is too small, or when users influence each other (marketplaces, social features). Then I use quasi-experiments such as difference-in-differences."

More practice: data analyst interview questions, how AI changed data analyst interviews and Python interview questions.

How to show this project on your resume

  • "Designed and analysed a 42,000-user checkout A/B test in Python (statsmodels, SciPy): power analysis, SRM check and z-test showed a +2.5-point conversion lift (95% CI +1.7 to +3.3)."
  • "Flagged a 2.5% drop in average order value and a novelty effect (+3.7 vs +2.2 points), recommended launch on +8.9% revenue per user, and showed by simulation that daily peeking inflates false positives from 5% to 23%."

Say the data is simulated if it is, and link the notebook. More ideas in data analysis projects and writing a data analyst resume.

Frequently asked questions

What is A/B testing in data analytics?

A/B testing is a randomised experiment that compares two versions of a product, page or message. Users are split at random between the current version (control) and the new one (treatment), and a pre-chosen metric such as conversion rate is compared with a statistical test to decide whether the change caused a real improvement.

How do you perform an A/B test in Python?

Calculate the sample size with statsmodels.stats.power.NormalIndPower, collect user-level data with the assigned group and outcome, check sample ratio mismatch with scipy.stats.chisquare, compare conversion rates with statsmodels.stats.proportion.proportions_ztest, and report the confidence interval with confint_proportions_2indep. Use Welch's t-test or Mann-Whitney for continuous metrics such as order value.

Which statistical test should I use for an A/B test?

For rates such as conversion or click-through, use a two-proportion z-test or a chi-square test; they give the same p-value for two groups. For continuous metrics such as order value or time spent, use Welch's t-test, and Mann-Whitney U if the data is very skewed. For more than two variants, correct for multiple comparisons.

How long should an A/B test run?

Run it until it reaches the sample size you calculated in advance, rounded up to whole weeks so all days of the week are covered. Most product tests run 1 to 4 weeks. Don't stop early because the result looks significant, and don't extend it because it's almost significant.

What is a good sample size for an A/B test?

It depends on the baseline rate and the smallest effect you want to detect. With a 22% conversion rate, detecting a 1.5-point lift at 5% significance and 80% power needs about 12,300 users per group, while detecting a 0.5-point lift needs about 108,600 per group.

What is the minimum detectable effect (MDE)?

The MDE is the smallest true effect your test is designed to detect reliably, given its sample size, significance level and power. Choose it from business value: the smallest lift that would justify building and maintaining the change. Smaller MDEs need far more users.

What is the difference between statistical significance and practical significance?

Statistical significance means the observed effect is unlikely to be due to chance alone. Practical significance means the effect is large enough to matter for the business. A huge test can find a tiny, statistically significant effect that isn't worth shipping, so compare the confidence interval with your MDE.

What tools are used for A/B testing?

Product teams use experimentation platforms such as Optimizely, VWO, Statsig, GrowthBook, Eppo, Amplitude Experiment, LaunchDarkly and Firebase A/B Testing, or build their own. Analysts often run the analysis in Python, R or SQL on the raw event data, which is the skill this guide teaches.

Recommended reading and practice on Skillancy

Sources

Reproducibility note

All code was run in order on 30 November 2026 with Python 3.13, NumPy 2.3.5, pandas 2.3.3, SciPy 1.18.1, statsmodels 0.15.0 and Matplotlib 3.11.2, and every output above is copied from that run. The experiment data is simulated with fixed seeds, and the true effects are known: +1.8 points of conversion lift, a novelty bump that fades over the first days, a 1.5% smaller order value and a 0.3-point rise in payment failures in the treatment. The simulated estimates land near those values, not exactly on them, which is the point of the exercise. A few long tables are shortened with "...", and the chart-drawing code is omitted from the post.

Learn it live: A/B test design, sample size and power, and communicating results to stakeholders are taught hands-on in Data Science with AI, where you analyse a checkout A/B test as a graded project. For the analyst path, Data Analytics with Agentic AI builds the statistics, SQL and Python foundations analysts use to report experiment results. Not sure which fits you? Talk to a mentor. Learn. Build. Get hired.
Newsletter

Get the Skillancy field notes

One email a week: AI and analytics guides, cohort dates and hiring signals. No spam, unsubscribe anytime.