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
- Read the code line by line.
- Track variable values in your head (or on paper).
- Watch out for side effects: function calls, list modifications, print statements.
- Consider scope: variables inside functions vs. global.
- 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
Nonereturns 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 beatsnotbeatsandbeatsor. When mixed, parentheses are the only tiebreaker โ evaluate left to right otherwise (except**, which groups right:2 ** 3 ** 2is2 ** 9). - Floor division and modulo with negatives:
-7 // 2is-4(it rounds down, toward negative infinity), and-7 % 2is1so that(a // b) * b + (a % b) == astays true. - Slices never raise:
"abc"[10:20]is a quiet empty string, unlike"abc"[10]which is an IndexError. Silent truncation, not an error. printreturns None:x = print("hi")prints, thenxisNoneโ 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(); onlysorted()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
whileis checked before, not after, the body โ off-by-one lives here.
๐ The Prediction Loop: How to Actually Get Better
- Predict in writing. Not in your head โ write the exact output, line by line, including spacing. "I knew it" is not a prediction.
- Run once. Compare character by character; near-misses still count as wrong (an extra blank line is wrong output).
- 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.
- 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
- Whitespace: does each
printadd a newline, useend=, or join with a separator? Match the output line-for-line. - Types:
3vs'3'vs3.0print differently;1 / 3is0.3333333333333333, not0.33. - Collections: list repr has brackets, tuple has commas, set order is not guaranteed โ predict membership, not sequence, if
{...}prints. - Loop edges: count iterations twice โ once from memory of
range, once by walking the first and last iteration on paper. - 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.