Skip to content
Exercises · Q5

Q.Write the output of the following:

a)
num1 = 4
num2 = num1 + 1
num1 = 2
print (num1, num2)
b)
num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print (num1, num2)
c)
num1, num2 = 2, 3
num3, num2 = num1, num3 + 1
print (num1, num2, num3)
Yanam BieapTextbookSubjective· 3mImportance★★★★★est
65% · 32/49 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

a) prints 2 5 (num2 kept the old num1+1); b) prints 6 4 (the right-hand tuple is built from the OLD values before any assignment); c) crashes with NameError — num3 appears on the right side before it exists.

The idea — assignment order. Two rules decide all three parts: (1) an assignment uses the values variables have at that moment — later changes don't back-propagate; (2) in a parallel assignment the entire right-hand side is evaluated first, then unpacked left to right.

a)

num1 = 4
num2 = num1 + 1     # num2 = 5 (uses num1's value NOW)
num1 = 2            # num2 is unaffected
print (num1, num2)
Statementnum1num2
num1 = 44—
num2 = num1 + 145
num1 = 225

Output: 2 5

b)

num1, num2 = 2, 6
num1, num2 = num2, num1 + 2   # RHS = (6, 2+2) = (6, 4), THEN assigned
print (num1, num2)
Statementnum1num2
num1, num2 = 2, 626
RHS builds (6, 4), unpacks64

Output: 6 4

c)

num1, num2 = 2, 3
num3, num2 = num1, num3 + 1   # RHS needs num3 -> it does not exist yet!
print (num1, num2, num3)
``` …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.