Python Data Types and Variables Questions and Answers — Questions and Answers
Question 1: Which of the following data types is immutable in Python?
- list
- dict
- set
- tuple (Correct answer)
Correct answer: tuple
In Python, immutable data types are those that cannot be changed after they are created. Tuples, defined with parentheses, are immutable. Once a tuple is created, its elements cannot be altered, added, or removed. Lists, dictionaries, and sets are all mutable, meaning their contents can be changed after creation.
Question 2: What will be the output of the following Python code? x = 5 y = '10' print(x + int(y))
- "510"
- 15 (Correct answer)
- TypeError
- 10
Correct answer: 15
The code first initializes an integer variable `x` to 5 and a string variable `y` to '10'. The `int()` function is used for type casting, converting the string '10' into the integer 10. Then, the addition operation `x + 10` is performed, which results in `5 + 10 = 15`. The `print()` function then outputs this result.
Question 3: A programmer is creating a script to store user configurations that should not change during program execution. Which data type is most appropriate for storing a collection of these configuration settings?
- list
- tuple (Correct answer)
- dictionary
- set
Correct answer: tuple
A tuple is the most appropriate choice because it is an immutable data type. This means that once the configuration settings are stored in a tuple, they are protected from accidental modification during the program's execution, ensuring data integrity.
Question 4: Which of the following is an invalid variable name in Python?
- _my_var
- myVar2
- 2myVar (Correct answer)
- MYVAR
Correct answer: 2myVar
Python variable names must start with a letter (a-z, A-Z) or an underscore (_). They cannot begin with a digit. Therefore, '2myVar' is an invalid variable name. '_my_var', 'myVar2', and 'MYVAR' are all valid.
Question 5: Consider the following code snippet: def my_func(): x = 10 print(x) x = 20 my_func() print(x)
- 10 20 (Correct answer)
- 20 10
- 10 10
- 20 20
Correct answer: 10 20
This question tests understanding of variable scope. The `x = 20` assignment creates a global variable. Inside `my_func()`, `x = 10` creates a new local variable `x` that shadows the global one. The `print(x)` inside the function prints the local `x` (10). After the function call, the `print(x)` in the global scope prints the global `x` (20).
Question 6: What is the data type of the result of the expression `10 / 4`?
- int
- float (Correct answer)
- tuple
- str
Correct answer: float
In Python 3, the standard division operator `/` always performs float division, meaning the result will be a float even if the numbers divide evenly. `10 / 4` results in `2.5`, which is a float data type. Integer division is performed with the `//` operator.
Which of the following data types is immutable in Python?