โ† Back to PyDebug

Predict Python Output โ€” Practice & Examples

๐Ÿง  Why Predict Python Output?

Predicting Python output is a core coding-interview and debugging skill: you read a snippet and work out exactly what it prints before you run it. Use this page to practice Python output prediction with step-by-step examples and the language rules behind them, then test yourself on PyDebug's interactive output-prediction problems.

How to Predict Stepโ€‘byโ€‘Step

  1. Read the code line by line.
  2. Track variable values in your head (or on paper).
  3. Watch out for side effects: function calls, list modifications, print statements.
  4. Consider scope: variables inside functions vs. global.
  5. Look for loops and conditionals โ€“ trace each iteration.

Example 1

x = 5
y = 10
if x < y:
    x = x + 2
print(x)

Prediction: 7 (since 5 < 10, x becomes 7).

Example 2 โ€“ Function with default mutable

def append_to(element, lst=[]):
    lst.append(element)
    return lst

print(append_to(1))
print(append_to(2))

Prediction: [1] then [1, 2] (the default list persists).

Example 3 โ€“ Loop and print

for i in range(3):
    print(i, end=" ")

Output: 0 1 2

Tips

  • Use end=" " in print to avoid newlines.
  • Watch for None returns from functions without explicit return.
  • Indentation changes can alter loop scope.

Example 4 โ€“ truthiness and the empty collection

items = []
if not items:
    print("empty")
else:
    print(items[0])

value = "0"
print(bool(value))   # True โ€” a non-empty string is truthy even when it looks "zero"

Prediction walkthrough: not [] is True, so the first print fires. Then bool("0") is True โ€” truthiness is about emptiness, not numeric value. Interviewers love this pair of lines precisely because intuition says "0 is false".

Example 5 โ€“ dictionary lookups and defaults

scores = {"ann": 7}
print(scores.get("bob", 0) + scores["ann"])
scores["cat"] = scores.get("cat", 10) + 1
print(sorted(scores))

Trace: get("bob", 0) returns 0, plus 7 โ†’ prints 7 โ€” but note that get() never stores the default, so "bob" is still absent. Then cat is missing โ†’ 10 + 1 = 11 is assigned, so the dict now has exactly two keys. sorted(scores) sorts the keys โ†’ prints ['ann', 'cat']. Two rules in one snippet: .get() with a default does not mutate, and sorting a dict sorts its keys, not its values.

๐Ÿ“ The Language Rules Predictions Are Made Of

Every prediction question is built from a short list of rules. Internalise these and the answers stop being guesses:

  • Precedence: ** beats *///%, which beat +/-; comparison beats not beats and beats or. When mixed, parentheses are the only tiebreaker โ€” evaluate left to right otherwise (except **, which groups right: 2 ** 3 ** 2 is 2 ** 9).
  • Floor division and modulo with negatives: -7 // 2 is -4 (it rounds down, toward negative infinity), and -7 % 2 is 1 so that (a // b) * b + (a % b) == a stays true.
  • Slices never raise: "abc"[10:20] is a quiet empty string, unlike "abc"[10] which is an IndexError. Silent truncation, not an error.
  • print returns None: x = print("hi") prints, then x is None โ€” a favourite trick in assignment-plus-function problems.
  • Mutators return None: lst = lst.append(4) destroys the list. The same trap exists for .sort() and .insert(); only sorted() gives you a new list.
  • Strings are immutable: s.replace("a", "b") produces a copy; unless you capture it, nothing happened.
  • Loop bodies update once per iteration: a counter printed inside a while is checked before, not after, the body โ€” off-by-one lives here.

๐Ÿ” The Prediction Loop: How to Actually Get Better

  1. Predict in writing. Not in your head โ€” write the exact output, line by line, including spacing. "I knew it" is not a prediction.
  2. Run once. Compare character by character; near-misses still count as wrong (an extra blank line is wrong output).
  3. Explain the delta. For every mismatch, write the one language rule that produced it โ€” "slices exclude the end", "default args are shared". That sentence is the lesson.
  4. Log and repeat. Keep a running list of your personal gotchas; re-test yourself a week later. Two weeks of ten minutes a day typically removes the same three recurring mistakes from your interview performance.

This is the exact drill behind PyDebug's prediction problems โ€” the editor hides the run button for a reason, and your XP and streak on the practice dashboard only move when the written answer matches. If a rule here is unfamiliar, the glossary defines it, and the debugging guide shows what to do when your mental model and the interpreter disagree.

๐Ÿงฎ Example 6 & 7 โ€” Precedence and Boundaries, Exam-Style

print(2 ** 3 ** 2)        # 512 โ€” ** groups right: 2 ** (3 ** 2), not (2 ** 3) ** 2
print(-7 // 2, -7 % 2)    # -4 1  โ€” floor, not truncate; the pair always recombines
s = "abcdefg"
print(s[2:5], s[-3:], s[::-1][:2], s[4:2])
# 'cde' 'efg' 'gf' '' โ€” start inclusive, stop exclusive, negative step reverses,
# and an empty slice never raises โ€” only out-of-range indexing does.

Both snippets show the same exam trick: three short operators competing for the rule your muscle memory applies. The fix is mechanical โ€” on paper, insert parentheses exactly where Python would (precedence), and count indices explicitly (start/stop) instead of squinting.

โœ… Before You Submit an Answer: A Five-Item Check

  1. Whitespace: does each print add a newline, use end=, or join with a separator? Match the output line-for-line.
  2. Types: 3 vs '3' vs 3.0 print differently; 1 / 3 is 0.3333333333333333, not 0.33.
  3. Collections: list repr has brackets, tuple has commas, set order is not guaranteed โ€” predict membership, not sequence, if {...} prints.
  4. Loop edges: count iterations twice โ€” once from memory of range, once by walking the first and last iteration on paper.
  5. Side effects: did any function mutate a shared list or default? Trace every caller, not just the last one.

Keep this checklist next to the prediction drill below; after two weeks of using it, the five checks collapse into habit and the misses stop being format errors.

Every item you miss is a topic to drill: the glossary defines the exact term, and the tutorials page sequences the prerequisite concepts before your next practice session.