What will the following code snippet print?
d = {} d.setdefault('a', []).append(1) print(d['a'])
KeyError: 'a'
[1]
[]
1
How can you create a dictionary where the keys are numbers from 1 to 5 and the values are their squares using a dictionary comprehension?
[i: i**2 for i in range(1, 6)]
{i**2: i for i in range(1, 5)}
(i: i**2 for i in range(1, 6))
{i: i**2 for i in range(1, 6)}
What is the purpose of using a default argument in a Python function?
To define a variable that can only be accessed within the function.
To specify a value for an argument if it is not passed in the function call.
To create a function that can accept any number of arguments.
To make the function return a default value if no arguments are provided.
In Python, what is the difference between a class variable and an instance variable?
There is no difference; they are interchangeable terms.
Class variables can only store integers, while instance variables can store any data type.
Class variables are declared inside a method, while instance variables are declared outside methods.
Class variables are shared by all instances of a class, while instance variables are unique to each instance.
Which module would you use to interact with the operating system, like creating directories?
os
math
datetime
sys
What is the purpose of the 'r' prefix in a regular expression pattern?
It treats the pattern as a raw string, ignoring escape sequences.
It enables multiline matching.
It performs a greedy match.
It makes the pattern case-insensitive.
What is the purpose of the 'r' mode in the following Python code?
file = open('data.txt', 'r')
Append data to an existing file.
Create a new file for writing.
Read and write to the file.
Open the file in read mode.
What is the output of the following Python code:
string = 'Hello, world!' print(string.replace('o', '0', 1))
Hello, world!
Hell0, w0rld!
Hell0, world!
Error
How can you handle potential errors when opening a file in Python?
Using a for loop.
Using a while loop.
Using an if-else statement.
Using a try-except block.
What does inheritance allow in object-oriented programming?
Restricting access to certain data and methods within a class.
Creating objects of one class inside another class.
Creating new classes that inherit properties and methods from existing classes.
Defining methods with the same name but different implementations in different classes.