LearnFrenzy
Sign in Take a free test

Python Programming · Topic 24 of 25

Tricky Python Output Questions Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Tricky Python Output Questions · Study material

"What is the output of the following code?" is the most common Python question in campus placement tests, online assessments and technical interviews. The programs are short, but each hides one trap: a list shared by two names, a default argument created once, round(2.5) giving 2, a generator that has run dry, a finally that runs before a return. This topic collects those traps in one place, explains why Python behaves that way, and drills them with 30 predict-the-output questions plus 10 MCQs and 10 find-the-error programs – every answer taken from a real run on Python 3. For questions on a single topic, see the output questions of every Python topic.

On this page

  • Names and objects: aliasing, + versus +=, chained assignment
  • Numbers: floor division, rounding, float error, equal keys
  • Truthiness, and / or, and methods that return None
  • Functions: mutable defaults, late binding, generators, scope
  • Classes and control flow: shared class attributes, finally, else
  • A method for solving any output question

Trap 1: names refer to objects

Assignment never copies. b = a gives one list two names, a += [3] changes that list in place, but a = a + [3] builds a new list and moves only a. For immutable objects (ints, strings, tuples) every "change" creates a new object, so other names are unaffected.

a = [1, 2]
b = a                 # same list
a = a + [3]           # + builds a NEW list; b still sees the old one
print(b)

c = [1, 2]
d = c
c += [3]              # += extends the SAME list; d sees it
print(d)

x = y = []            # chained assignment: one list, two names
x.append("!")
p = q = 0
p += 1                # ints are immutable: p is rebound, q untouched
print(y, q)

Output

[1, 2]
[1, 2, 3]
['!'] 0

Trap 2: numbers

// floors toward minus infinity while int() truncates toward zero; % takes the sign of the divisor. round() sends halves to the even neighbour. Binary floats make 0.1 + 0.2 slightly more than 0.3. Because 1 == 1.0 == True with equal hashes, they are the same dictionary key (the first key object is kept, the last value wins). / always returns a float.

print(7 // 2, -7 // 2, -7 % 2, int(-3.7))        # floor division vs truncation
print(round(0.5), round(1.5), round(2.5), round(-2.5))   # halves go to the even neighbour
print(0.1 + 0.2 == 0.3, round(0.1 + 0.2, 10) == 0.3)
print({1: "int", 1.0: "float", True: "bool"})     # 1 == 1.0 == True: one key
print(10 / 5, type(10 / 5).__name__)              # / always gives a float

Output

3 -4 1 -3
0 2 2 -2
False True
{1: 'bool'}
2.0 float

Trap 3: truthiness, and/or, and None

and and or return one of their operands, not True/False. An empty list is falsy but is not equal to False. Methods that modify a list in place (sort, append, reverse) return None, and so does print.

print(0 or "default", [] and "never", "a" and "b", None or [] or 0)   # and/or return OPERANDS
print([] == False, bool([]) == False, not [])                         # falsy is not "equal to False"

nums = [3, 1, 2]
print(nums.sort(), nums)          # list methods that change the list return None
print(print("hi") is None)        # print returns None too

Output

default [] b 0
False True True
None [1, 2, 3]
hi
True

Trap 4: functions

Default values are evaluated once, when def runs – a mutable default is shared by every call. Lambdas and inner functions look up outer variables when they are called (late binding). Generators can be consumed only once. A function reads a global's value at call time, not at definition time.

def add(item, bag=[]):            # the default list is created ONCE
    bag.append(item)
    return bag

print(add(1), add(2))

funcs = [lambda: i for i in range(3)]   # lambdas read i when CALLED
print([f() for f in funcs])

g = (n * n for n in range(4))     # generators run once
print(sum(g), sum(g))

x = 5
def show():
    return x                      # reads the global at call time
x = 50
print(show())

Output

[1, 2] [1, 2]
[2, 2, 2]
14 0
50

Trap 5: classes and control flow

A mutable class attribute is one object shared by every instance. finally runs even when try returns – before the caller receives the value. else runs only when try raised nothing.

class Team:
    members = []                  # shared by every instance

t1, t2 = Team(), Team()
t1.members.append("Asha")
print(t2.members)

def f():
    try:
        return "try"
    finally:
        print("finally runs before the return completes")

print(f())

for i in range(3):
    try:
        if i == 1:
            raise ValueError
    except ValueError:
        print("E", end="")
    else:
        print("O", end="")
    finally:
        print(i, end=" ")
print()

Output

['Asha']
finally runs before the return completes
try
O0 E1 O2

How to solve an output question

  1. Read top to bottom, executing statements in order – def and class only define.
  2. Keep a table of every name and the object it refers to; mark when two names share one object.
  3. Ask "new object or same object?" for every assignment, +, += and method call.
  4. Check the special rules: integer vs float division, rounding, truthiness, default arguments, scope.
  5. Write the output exactly – spaces from print's sep, end="", quotes from repr, brackets of lists and tuples.

Key points to remember

  • = binds a name; += on a list mutates; + creates a new list.
  • // floors, int() truncates, round() rounds halves to even.
  • and / or return operands; [] == False is False.
  • sort(), append(), print() return None.
  • Defaults are evaluated once; lambdas bind late; generators run once.
  • Mutable class attributes are shared.
  • finally always runs; else runs only without an exception.

Frequently asked questions

Why are output questions so common in tests?

They check whether you understand how Python actually executes code – references, scope, evaluation order – rather than whether you remember syntax.

Should I memorise these outputs?

Memorise the rules, not the answers. Every question here follows from one of the five traps above.

How can I check my answer?

Paste the code into the online Python compiler and run it, or use the Python visualizer to watch every name and object change step by step.

Where can I learn more?

Revise Python Variables and Python Lists in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links