Python Programming - Variables

Exercise : Variables - General Questions
  • Variables - General Questions
31.
What is the output of the following code:
my_dict = {"a": 1, "b": 2}
my_dict["c"] = 3
print(my_dict)
{"a": 1, "b": 2}
{"a": 1, "b": 2, "c": 3}
{"c": 3}
An error is raised
Answer: Option
Explanation:

In this code, a dictionary my_dict is defined with two key-value pairs.

The second line adds a new key "c" with the value 3 to the dictionary.

When the modified dictionary is printed to the console, the output is {"a": 1, "b": 2, "c": 3}.


32.
What is the output of the following code:
my_string = "hello world"
print(my_string[1:8:2])
eoo
el o
elwrd
hlowr
Answer: Option
Explanation:

In this code, a string my_string is defined with the value "hello world".

The second line uses slice notation to select every second character from the substring starting at index 1 and ending at index 8.

The expression my_string[1:8:2] selects the characters with the following indices: 1, 3, 5, and 7, which correspond to "el o" in the string "hello world".

The resulting substring is "el o", which is then printed to the console.


33.
Which of the following is a valid way to delete a key-value pair from a dictionary?
my_dict.delete("key")
del my_dict["key"]
my_dict.del("key")
All of the above are valid
Answer: Option
Explanation:

The del keyword can be used to remove a key-value pair from a dictionary. To delete the pair with key "key", you can use the syntax del my_dict["key"].

Other methods for removing key-value pairs from a dictionary include using the pop() method or the clear() method.

1. Using the pop() method:

my_dict.pop("key")

This method removes the key and returns its value. If the key is not found, a specified default value is returned, or a KeyError is raised.

2. Using the clear() method:

my_dict = {"a": 1, "b": 2, "c": 3}
my_dict.clear()
print(my_dict)  # Output: {}

It does not delete individual key-value pairs, but rather empties the entire dictionary.


34.
What is the output of the following code:
my_list = [1, 2, 3]
my_list.append([4, 5])
print(my_list)
[1, 2, 3]
[1, 2, 3, 4, 5]
[1, 2, 3, [4, 5]]
An error is raised
Answer: Option
Explanation:

In this code, a list my_list is defined with the values [1, 2, 3].

The second line appends the list [4, 5] to my_list.

When the modified list is printed to the console, the output is [1, 2, 3, [4, 5]].


35.
What is the output of the following code:
my_dict = {"a": 1, "b": 2}
del my_dict["c"]
print(my_dict)
{"a": 1, "b": 2}
{"a": 1, "b": 2, "c": None}
{"a": 1, "b": 2, "c": undefined}
An error is raised
Answer: Option
Explanation:

The given code attempts to delete the key "c" from the dictionary my_dict.

However, since "c" is not a valid key in the dictionary, the del my_dict["c"] operation will raise a KeyError.

Therefore, the output of the code will be a KeyError:

Traceback (most recent call last):
  File "example.py", line 2, in 
    del my_dict["c"]
KeyError: 'c'