Introducing Python — Question 1
Back to all questionsQuestion 1
(a) What will be the output produced by following code fragments ?
(i)
a, b = 2, 3
c, b = a, c + 1
print a, b, c(ii)
x, y = 2, 6
x, y = y, x + 2
print x, y(b) What will the output produced if we interchange the first two lines of above two codes [given in part (a)], e.g., as shown below for code (i) ? Will it give any error ? Give reason(s).
c, b = a, c + 1
a, b = 2, 3
print a, b, c(a)
(i) This code fragment will generate the below error:
NameError: name 'c' is not defined
Reason — The error is generated because in line 2, the variable c is not defined before being used.
(ii)
Output
6 4
Explanation
| Statement | Value of X | Value of Y | Remark |
|---|---|---|---|
| x, y = 2, 6 | 2 | 6 | Both x, y are initialized |
| x, y = y, x + 2 | 6 | 4 | x = 6, y = 2 + 2 = 4 |
| print (x, y) | 6 | 4 | 6 (x), 4 (y) are printed |
(b) When we interchange the first two lines of above codes, we get the following outputs:
(i) It will give the same error as before because even after interchanging first two lines variable C is still used before it is defined.
(ii) Interchanging the first two lines will generate the below error:
NameError: name 'y' is not defined
Reason — The error is generated because now in line 1, the variable y is not defined before being used.