Exercise: Python

Questions for: Variables

Which of the following statements about Python variables is true?
A:
Python is a statically typed language.
B:
A variable must be declared with a type before it can be used.
C:
Python allows multiple assignments in a single line.
D:
A variable's scope is determined by the type of data it holds.
Answer: C
Python is a dynamically typed language. In Python, a variable's type is inferred from the value it's assigned. A variable's scope is determined by where it's defined in the code.

For example:

a, b, c = 1, 2, 3

This statement assigns the values 1, 2, and 3 to the variables a, b, and c, respectively.

You can also assign the same value to multiple variables in one line:

a = b = c = "Orange"

This statement assigns the value "Orange" to the variables a, b, and c.

If you have a collection of values in a list, tuple, etc. Python allows you to extract the values into variables. This is called unpacking. For example:

fruits = ["apple", "banana", "cherry"]
a, b, c = fruits

This statement extracts the values "apple", "banana", and "cherry" from the list fruits and assigns them to the variables a, b, and c, respectively.

What is the output of the following code:
my_string = "hello"
my_string[1] = "a"
print(my_string)
A:
hello
B:
hallo
C:
An error is raised
D:
None of the above
Answer: C

In Python, strings are immutable, which means their individual characters cannot be modified once they're created.

Attempting to change a character of a string using the index operator [ ] results in a TypeError.

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

In this code, the variable my_list is initially assigned a list containing the values 1, 2, and 3.

The second element of the list (which has an index of 1) is then changed to 4 using the assignment operator =.

When my_list is printed to the console, it shows the modified list [1, 4, 3].

Which of the following is a valid way to check if a value is in a list called my_list?
A:
if my_value in my_list
B:
if my_list[ my_value ]
C:
if my_value in my_list == True
D:
All of the above
Answer: A
In Python, the in and not in operators can be used to check if a value is or is not in a list, respectively.
What is the value of y after executing the following code:
x = [1, 2, 3]
y = x
x = [4, 5, 6]
print(y)
A:
[4, 5, 6]
B:
[1, 2, 3]
C:
[1, 2, 3, 4, 5, 6]
D:
An error is raised
Answer: B

In this code, the variable x is initially assigned a list containing the values 1, 2, and 3.

The variable y is then assigned the same list that x holds a reference to.

However, when x is reassigned a new list containing the values 4, 5, and 6, y still holds a reference to the original list [1, 2, 3].

So when y is printed to the console, it prints [1, 2, 3].

Ad Slot (Above Pagination)
Quiz