KnowledgeBoat Logo
|

Computer Applications

(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

Python Funda

11 Likes

Answer

(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
StatementValue of XValue of YRemark
x, y = 2, 626Both x, y are initialized
x, y = y, x + 264x = 6, y = 2 + 2 = 4
print (x, y)646 (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.

Answered By

3 Likes


Related Questions