Python Questions and Answers Part-11

1. What will be the output of the following Python code snippet?
for i in ''.join(reversed(list('abcd'))):
print (i)
a) a b c d
b) d c b a
c) error
d) none of the mentioned

Answer: b
Explanation: ‘ ‘.join(reversed(list(‘abcd’))) reverses a string

2. What will be the output of the following Python code snippet?
for i in 'abcd'[::-1]:
print (i)
a) a b c d
b) d c b a
c) error
d) none of the mentioned

Answer: b
Explanation: [::-1] reverses the string.

3. What will be the output of the following Python code snippet?
for i in '':
print (i)
a) None
b) nothing is printed
c) error
d) none of the mentioned

Answer: b
Explanation: The string does not have any character to loop over.

4. What will be the output of the following Python code snippet?
x = 2
for i in range(x):
x += 1
print (x)
a) 0 1 2 3 4 …
b) 0 1
c) 3 4
d) 0 1 2 3

Answer: c
Explanation: Variable x is incremented and printed twice.

5. What will be the output of the following Python code snippet?
x = 2
for i in range(x):
x -= 2
print (x)
a) 0 1 2 3 4 …
b) 0 -2
c) 0
d) error

Answer: b
Explanation: The loop is entered twice

6. What will be the output of the following Python statement?
>>>"a"+"bc"
a) a
b) bc
c) bca
d) abc

Answer: d
Explanation: + operator is concatenation operator.

7. What will be the output of the following Python statement?
>>>"abcd"[2:]
a) a
b) ab
c) cd
d) dc

Answer: c
Explanation: Slice operation is performed on string.

8. The output of executing string.ascii_letters can also be achieved by:
a) string.ascii_lowercase_string.digits
b) string.ascii_lowercase+string.ascii_uppercase
c) string.letters
d) string.lowercase_string.uppercase

Answer: b

9. What will be the output of the following Python code?
>>> str1 = 'hello'
>>> str2 = ','
>>> str3 = 'world'
>>> str1[-1:]
a) olleh
b) hello
c) h
d) o

Answer: d
Explanation: -1 corresponds to the last index.

10. What arithmetic operators cannot be used with strings?
a) +
b) *
c) -
d) All of the mentioned

Answer: c
Explanation: + is used to concatenate and * is used to multiply strings.