POC Core Python Programming Concepts 2 — Questions and Answers
Question 1: What is the output of `print(type(lambda x: x))`?
- <class 'function'> (Correct answer)
- <class 'lambda'>
- <class 'method'>
- <class 'object'>
Correct answer: <class 'function'>
Lambda expressions create anonymous function objects, so their type is 'function'.
Question 2: Which of the following correctly unpacks a dictionary into keyword arguments?
- func(*my_dict)
- func(**my_dict) (Correct answer)
- func(my_dict)
- func(&my_dict)
Correct answer: func(**my_dict)
The `**` operator unpacks a dictionary into keyword arguments when calling a function.
Question 3: What does the `global` keyword do inside a function?
- Creates a new global variable only
- Imports a variable from another module
- Declares that a variable refers to the global scope (Correct answer)
- Prevents the variable from being modified
Correct answer: Declares that a variable refers to the global scope
The `global` keyword tells Python to use the variable from the global (module-level) scope rather than creating a local one.
Question 4: What is the result of `[x**2 for x in range(4) if x % 2 == 0]`?
- [0, 4] (Correct answer)
- [1, 9]
- [0, 1, 4, 9]
- [4, 16]
Correct answer: [0, 4]
range(4) gives 0,1,2,3; filtering even values gives 0 and 2; squaring gives [0, 4].
Question 5: Which exception is raised when accessing a dictionary key that does not exist?
- IndexError
- ValueError
- KeyError (Correct answer)
- AttributeError
Correct answer: KeyError
Python raises a KeyError when you attempt to access a dictionary with a key that is not present.
Question 6: What is the purpose of `__init__` in a Python class?
- It is called when the class is imported
- It initializes a new instance of the class (Correct answer)
- It defines class-level variables only
- It is the destructor method
Correct answer: It initializes a new instance of the class
`__init__` is a special method called automatically when a new object is instantiated to set up its initial state.
Question 7: What does `*args` allow a function to accept?
- Only keyword arguments
- A fixed number of positional arguments
- An arbitrary number of positional arguments (Correct answer)
- Arguments from a dictionary
Correct answer: An arbitrary number of positional arguments
`*args` collects any number of extra positional arguments into a tuple inside the function.
What is the output of `print(type(lambda x: x))`?