Showing 21–30 of 56 questions
Consider: d = {1: 'a', 2: 'b', 3: 'c'}. What is d.get(4, 'default')?
A
'c'
B
None
C
'default'
D
Error
Correct Answer:
C. 'default'
EXPLANATION
The get() method returns a value for a key. If the key doesn't exist, it returns the default value provided.
What will be the result of: ' hello '.strip()?
A
' hello'
B
'hello '
C
'hello'
D
'HELLO'
Correct Answer:
C. 'hello'
EXPLANATION
The strip() method removes leading and trailing whitespace. ' hello '.strip() returns 'hello'.
Consider: result = [x*2 for x in range(3) if x > 0]. What is result?
A
[0, 2, 4]
B
[2, 4]
C
[0, 1, 2]
D
[1, 2, 3]
Correct Answer:
B. [2, 4]
EXPLANATION
List comprehension iterates through range(3) [0,1,2], filters x>0 [1,2], and multiplies by 2: [2, 4].
What will be the output of: print(isinstance(5, int))?
A
True
B
False
C
None
D
Error
EXPLANATION
isinstance() checks if an object is an instance of a class. 5 is an integer, so isinstance(5, int) returns True.
Consider the code: x = 5; y = x; x = 10. What is the value of y?
EXPLANATION
When y = x is executed, y gets the value 5. Later changing x to 10 does not affect y's value because integers are immutable.
What is the output of: print(5 == '5')?
A
True
B
False
C
Error
D
None
EXPLANATION
The == operator compares values and types. 5 (integer) and '5' (string) are different types, so the result is False.
Consider: lst = [1, 2, 3, 2, 1]. What will lst.count(2) return?
EXPLANATION
The count() method returns the number of occurrences of an element. 2 appears twice in the list.
What will be printed: for i in range(1, 4): print(i, end=' ')?
A
0 1 2 3
B
1 2 3
C
1 2 3 4
D
0 1 2
EXPLANATION
range(1, 4) generates numbers from 1 to 3 (4 is excluded). The end=' ' parameter prints with space separator.
Consider the code: def func(a, b=5): return a + b. What is func(3)?
EXPLANATION
b has a default value of 5. When func(3) is called, a=3 and b=5 (default), so return 3+5=8.
Which of the following will correctly check if a key exists in a dictionary?
A
if key in dict:
B
if dict.has_key(key):
C
if dict[key]:
D
if key.exists(dict):
Correct Answer:
A. if key in dict:
EXPLANATION
The 'in' operator checks for key existence in a dictionary. has_key() was removed in Python 3.