Exercise: Python

Questions for: Variables

What is the output of the following code:
my_dict = {"a": 1, "b": 2}
my_dict["c"] = 3
print(my_dict)
A:
{"a": 1, "b": 2}
B:
{"a": 1, "b": 2, "c": 3}
C:
{"c": 3}
D:
An error is raised
Answer: B

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}.

Which of the following is true about the pass statement?
A:
It is a keyword used to create empty code blocks.
B:
It is used to terminate a loop or a function.
C:
It is used to raise an exception.
D:
It is not a valid keyword in Python.
Answer: A

The pass statement in Python is used as a placeholder for code that has not been implemented yet.

It is a keyword that creates an empty code block and does nothing. It is commonly used when defining functions, loops, and conditional statements that will be filled in later.

What is the output of the following code:
x = 5
y = x
x = 10
print(y)
A:
5
B:
10
C:
An error is raised
D:
None of the above
Answer: A

In this code, a variable x is assigned the value 5, and a variable y is assigned the same value by copying the value of x.

The value of x is then changed to 10, but the value of y remains unchanged at 5.

When the value of y is printed to the console, the output is 5.

Which of the following is NOT a valid way to declare a tuple?
A:
my_tuple = 1, 2, 3
B:
my_tuple = (1, 2, 3)
C:
my_tuple = tuple(1, 2, 3)
D:
All of the above are valid
Answer: C

my_tuple = tuple(1, 2, 3) is not a valid way to declare a tuple in Python.

Instead, you can use my_tuple = 1, 2, 3 or my_tuple = (1, 2, 3) to create a tuple directly, or use the tuple() function to convert another iterable (like a list) into a tuple.

For example: my_tuple = tuple([1, 2, 3])

What is the output of the following code:
my_list = [1, 2, 3, 4]
my_list[1:3] = [5, 6]
print(my_list)
A:
[1, 2, 3, 4]
B:
[1, 5, 6, 4]
C:
[1, 2, 5, 6, 4]
D:
An error is raised
Answer: B

In this code, a list my_list is defined with four elements.

The second line uses slice assignment to replace the second and third elements of the list with the new list [5, 6].

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

Ad Slot (Above Pagination)
Quiz