Skip to content
CodeKruPro

Predict the output · Python

Operators, conditions and loops

Increment operators, precedence, short-circuiting and loop counts.

Learn: Predicting Python operators, conditions and loops7 minute read

Python operators hold several surprises for people who know Java or C. Interviewers use short operator and loop snippets to check that you know Python itself, not just a general idea of programming, and that you can trace code carefully, the same skill you need to debug a failing test. These are the rules that matter.

Rule 1: there is no ++ or --

++x is valid Python, but it means +(+x): two unary plus signs (a plus sign with a single value after it). It computes the same value and changes nothing. --x is minus of minus. No error is raised, which is what makes it a trap. To change a variable, write x += 1.

Rule 2: comparisons chain

a < b < c means a < b and b < c, with b evaluated once. This also applies to mixes such as 1 < x > 3, and to ==, in and is, which are comparison operators too. (in asks whether a value is inside a list or text. is asks whether two names point at the same object.) So 1 in [1, 2] == True means 1 in [1, 2] and [1, 2] == True, which is False.

Rule 3: and and or return an operand

A value is truthy if it counts as true in an if, and falsy otherwise. The common falsy values are False, None, 0, 0.0 and empty strings, lists, tuples (fixed groups of values), dicts (dictionaries, which store key and value pairs) and sets. or returns the first truthy operand, or the last operand when none is truthy. and returns the first falsy operand, or the last operand when all are truthy. Both operators stop as soon as the answer is known (short-circuiting), so later function calls may never run.

Rule 4: precedence of ** and not

** (power) is applied before a minus sign in front of it, so -3 ** 2 is -9. It also groups from right to left, so 2 ** 2 ** 3 is 2 to the power 8. not is applied after comparisons, so not a == b means not (a == b). *, /, // and % share one level and go from left to right.

x = 4
print(2 < x <= 4, 1 < x > 5)
print(0 or "none", 3 and 0)
print(-3 ** 2, 2 ** 2 ** 3)
True False
none 0
-9 256

Rule 5: range stops before the end

range(start, stop, step) includes start and stops before stop. A negative step counts down, and the stop is still excluded. len(range(...)) tells you how many passes a loop makes.

Rule 6: the loop variable is reassigned each pass

A for loop takes the next value from its iterable (anything you can loop over, such as a list or a range) at the start of every pass. Changing the loop variable inside the body does not skip or repeat anything. After the loop, the variable keeps its last value, including any change the body made in the last pass.

Rule 7: else on a loop means "no break"

A for or while loop may have an else block. It runs when the loop ends normally, and is skipped when the loop ends through break. It is a short way to write "search, and report when nothing was found".

for n in range(10, 0, -4):
    print(n, end=" ")
print()
for n in [1, 3]:
    if n == 2:
        break
else:
    print("no break")
10 6 2
no break

Tracing loops

For a while loop, write down the variables each time the condition is checked. Floor division (divide, then round down; see Numbers and arithmetic), as in n //= 3, makes values shrink fast, and the loop ends as soon as the condition is false. Count the passes, not the values.

How to answer in an interview

Say the rule you are applying as you go. "Python chains comparisons, so this is 1 < 5 and 5 > 3, which is True." "or returns the first truthy value, so it prints default." When the snippet looks like Java, such as ++x, point out the difference directly: Python has no increment operator, and the line does nothing.

Common mistakes

  • Expecting ++x to add 1.
  • Expecting and and or to always return True or False.
  • Reading -2 ** 2 as 4.
  • Including the stop value of range.
  • Thinking a loop's else runs after a break.

Recap

Python has no ++. Comparisons chain, including in and ==. and and or return one of their operands and stop early. ** is applied early and groups from the right, and not is applied late. range excludes its stop, the loop variable outlives the loop, and loop else means "no break".

10 questions0/10 solved

Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan