Exercises · Q5
Q.Write the output of the following:
a)
num1 = 4
num2 = num1 + 1
num1 = 2
print (num1, num2)
num1 = 4
num2 = num1 + 1
num1 = 2
print (num1, num2)
b)
num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print (num1, num2)
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)
num1, num2 = 2, 3
num3, num2 = num1, num3 + 1
print (num1, num2, num3)
Odisha ChseTextbookSubjective· 3mImportance★★★★★est
65% · 32/49 Questions
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)
| Statement | num1 | num2 |
|---|---|---|
| num1 = 4 | 4 | — |
| num2 = num1 + 1 | 4 | 5 |
| num1 = 2 | 2 | 5 |
Output: 2 5
b)
num1, num2 = 2, 6
num1, num2 = num2, num1 + 2 # RHS = (6, 2+2) = (6, 4), THEN assigned
print (num1, num2)
| Statement | num1 | num2 |
|---|---|---|
| num1, num2 = 2, 6 | 2 | 6 |
| RHS builds (6, 4), unpacks | 6 | 4 |
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.