Showing 1–10 of 20 questions
in Basics & Syntax
What is the output of: print(type(lambda x: x))?
EXPLANATION
Lambda functions are functions in Python. type(lambda x: x) returns <class 'function'>.
Consider: class A: x = 5. What is A.x and how can it be modified?
A
Instance variable, modify via obj.x
B
Class variable, modify via A.x or obj.x
C
Local variable, cannot be modified
D
Error
Correct Answer:
B. Class variable, modify via A.x or obj.x
EXPLANATION
x = 5 is a class variable. It can be accessed via A.x and modified via A.x = new_value or instance modification.
What will be the output of: print({x: x**2 for x in range(3)})?
A
{0: 0, 1: 1, 2: 4}
B
{0: 1, 1: 2, 2: 3}
C
{1: 1, 2: 4}
D
Error
Correct Answer:
A. {0: 0, 1: 1, 2: 4}
EXPLANATION
Dictionary comprehension creates {0: 0, 1: 1, 2: 4} where keys are from range(3) and values are their squares.
Consider the code: with open('file.txt') as f: data = f.read(). What happens when the block exits?
A
File remains open
B
File is automatically closed
C
Error occurs
D
data is deleted
Correct Answer:
B. File is automatically closed
EXPLANATION
The 'with' statement ensures the file is automatically closed when the block exits, even if an error occurs.
What is the output of: print(eval('2+3*4'))?
EXPLANATION
eval() evaluates the string as Python code following operator precedence. 2+3*4 = 2+12 = 14.
Consider: *a, b = [1, 2, 3]. What is a?
A
[1, 2]
B
1
C
[1, 2, 3]
D
Error
Correct Answer:
A. [1, 2]
EXPLANATION
The * operator in unpacking collects remaining elements. a gets [1, 2] and b gets 3.
What will be the result of: set([1, 2, 2, 3, 3, 3])?
A
{1, 2, 2, 3, 3, 3}
B
{1, 2, 3}
C
[1, 2, 3]
D
Error
Correct Answer:
B. {1, 2, 3}
EXPLANATION
Sets remove duplicate elements. set([1, 2, 2, 3, 3, 3]) returns {1, 2, 3}.
Consider: f = lambda x: x**2. What is f(5)?
EXPLANATION
Lambda creates an anonymous function. f = lambda x: x2 creates a function that returns x squared. f(5) = 52 = 25.
What is the output of: print(*[1, 2, 3])?
A
[1, 2, 3]
B
1 2 3
C
123
D
Error
EXPLANATION
The * operator unpacks the list. print(*[1, 2, 3]) becomes print(1, 2, 3) which prints '1 2 3' with spaces.
Consider: try: int('abc'); except: print('error'). What will be printed?
A
Nothing
B
'error'
C
error
D
ValueError
EXPLANATION
int('abc') raises a ValueError. The except block catches it and prints 'error' (without quotes).