## Python Questions and Answers Part-6

1. What will be the output of the following Python code snippet if x=1?
x<<2
a) 8
b) 1
c) 2
d) 4

Answer: d
Explanation: The binary form of 1 is 0001. The expression x<<2 implies we are performing bitwise left shift on x. This shift yields the value: 0100, which is the binary form of the number 4.

2. What will be the output of the following Python expression?
bin(29)
a) ‘0b10111’
b) ‘0b11101’
c) ‘0b11111’
d) ‘0b11011’

Answer: b
Explanation: The binary form of the number 29 is 11101. Hence the output of this expression is ‘0b11101’.

3. What will be the value of x in the following Python expression, if the result of that expression is 2?
x>>2
a) 8
b) 4
c) 2
d) 1

Answer: a
Explanation: When the value of x is equal to 8 (1000), then x>>2 (bitwise right shift) yields the value 0010, which is equal to 2. Hence the value of x is 8.

4. What will be the output of the following Python expression?
int(1011)?
a) 1011
b) 11
c) 13
d) 1101

Answer: a
Explanation: The result of the expression shown will be 1011. This is because we have not specified the base in this expression. Hence it automatically takes the base as 10.

5. To find the decimal value of 1111, that is 15, we can use the function:
a) int(1111,10)
b) int(‘1111’,10)
c) int(1111,2)
d) int(‘1111’,2)

Answer: d
Explanation: The expression int(‘1111’,2) gives the result 15. The expression int(‘1111’, 10) will give the result 1111.

6. What will be the output of the following Python expression if x=15 and y=12?
x & y
a) b1101
b) 0b1101
c) 12
d) 1101

Answer: c
Explanation: The symbol ‘&’ represents bitwise AND. This gives 1 if both the bits are equal to 1, else it gives 0. The binary form of 15 is 1111 and that of 12 is 1100. Hence on performing the bitwise AND operation, we get 1100, which is equal to 12.

7. Which of the following expressions results in an error?
a) int(1011)
b) int(‘1011’,23)
c) int(1011,2)
d) int(‘1011’)

Answer: c
Explanation: The expression int(1011,2) results in an error. Had we written this expression as int(‘1011’,2), then there would not be an error.

8. Which of the following represents the bitwise XOR operator?
a) &
b) ^
c) |
d) !

Answer: b
Explanation: The ^ operator represent bitwise XOR operation. &: bitwise AND, | : bitwise OR and ! represents bitwise NOT.

9. What is the value of the following Python expression?
bin(0x8)
a) ‘0bx1000’
b) 8
c) 1000
d) ‘0b1000’

Answer: d
Explanation: The prefix 0x specifies that the value is hexadecimal in nature. When we convert this hexadecimal value to binary form, we get the result as: ‘0b1000’.

10. What will be the output of the following Python expression?
0x35 | 0x75
a) 115
b) 116
c) 117
d) 118

Answer: c
Explanation: The binary value of 0x35 is 110101 and that of 0x75 is 1110101. On OR-ing these two values we get the output as: 1110101, which is equal to 117. Hence the result of the above expression is 117.