Python Pandas MCQ : Set 4

Python Pandas MCQ

1). What is the output of the following code?

				
					import pandas as pd
df = pd.Series([15, 43, 88, 23])
print(df)
				
			

a) 15, 43, 88, 23
b) [15, 43, 88, 23]
c) 0 15
1 43
2 88
3 23
dtype: int64
d) None of the above

Correct answer is: c) 0 15
1 43
2 88
3 23
dtype: int64
Explanation: The code creates a Pandas Series named `df` with values [15, 43, 88, 23]. When the `print(df)` statement is executed, it prints the Series object `df` along with the index and the data type. In this case, the output displays the index values (0, 1, 2, 3) and the corresponding data values (15, 43, 88, 23) with a dtype of int64.

2). What is the output of the following code?

				
					import pandas as pd
df = pd.Series([15, 43, 88, 23])
print(df)
print(type(df))
print("Convert Pandas Series to Python list")
print(df.tolist())
print(type(df.tolist()))
				
			

a)
0 15
1 43
2 88
3 23
dtype: int64
<class ‘pandas.core.series.Series’>
Convert Pandas Series to Python list
[15, 43, 88, 23]
<class ‘list’>

b) 0 15
1 43
2 88
3 23
dtype: int32
<class ‘pandas.core.series.Series’>
Convert Pandas Series to Python list
[15, 43, 88, 23]
<class ‘list’>

c) 15 43 88 23
<class ‘pandas.core.series.Series’>
Convert Pandas Series to Python list
[15, 43, 88, 23]
<class ‘list’>

d) 15 43 88 23
<class ‘pandas.core.series.Series’>
Convert Pandas Series to Python list
15 43 88 23
<class ‘list’>

Correct answer is: a)
0 15
1 43
2 88
3 23
dtype: int64
<class ‘pandas.core.series.Series’>
Convert Pandas Series to Python list
[15, 43, 88, 23]
<class ‘list’>
Explanation: The code first creates a Pandas Series object named `df` with the values `[15, 43, 88, 23]`. When printing `df`, it displays the Series with the index and values. Next, the code prints the type of `df`, which is `<class ‘pandas.core.series.Series’>`.After that, it prints “Convert Pandas Series to Python list” as a message. Following that, `df.tolist()` converts the Pandas Series `df` into a Python list. When printing `df.tolist()`, it displays the list of values `[15, 43, 88, 23]`.

3). What is the output of the following code?

				
					import pandas as pd
df1 = pd.Series([1,6,9,5])
df2 = pd.Series([5,2,4,5])
print(df1+df2)
				
			

a) [6, 8, 13, 10]
b) [1, 6, 9, 5, 5, 2, 4, 5]
c) [6, 8, 13, 10, NaN, NaN, NaN, NaN]
d) [1, 6, 9, 5, 5, 2, 4, 5, NaN, NaN, NaN, NaN]

Correct answer is: a) [6, 8, 13, 10]
Explanation: The code creates two Series, `df1` and `df2`, with the values [1, 6, 9, 5] and [5, 2, 4, 5] respectively. When we perform the addition operation `df1+df2`, Pandas aligns the Series based on their indices and performs element-wise addition. In this case, the resulting Series will be [1+5, 6+2, 9+4, 5+5], which simplifies to [6, 8, 13, 10]. Therefore, the output of the code will be [6, 8, 13, 10].

4). What is the output of the following code?

				
					import pandas as pd
df1 = pd.Series([1, 6, 9, 5])
df2 = pd.Series([5, 2, 4, 5])
print(df1 - df2)
				
			

a) [4, 4, 5, 0]
b) [6, 4, 5, 0]
c) [1, 4, 5, 0]
d) [4, 2, 5, 0]

Correct answer is: a) [4, 4, 5, 0]
Explanation: When subtracting two Series in Pandas, the operation is performed element-wise. In this case, `df1 – df2` subtracts the corresponding elements of `df2` from `df1`. Thus, the resulting Series is [4, 4, 5, 0].

5). What is the output of the following code?

				
					import pandas as pd
df1 = pd.Series([1, 6, 9, 5])
df2 = pd.Series([5, 2, 4, 5])
print(df1 * df2)
				
			

a) 5, 12, 36, 25
b) 5, 12, 36, 30
c) 5, 12, 36, 45
d) 5, 6, 36, 25

Correct answer is: c) 5, 12, 36, 45
Explanation: The code creates two pandas Series objects, `df1` and `df2`, with corresponding values [1, 6, 9, 5] and [5, 2, 4, 5]. When the multiplication operator `*` is applied to these two Series, element-wise multiplication is performed) Therefore, the resulting Series will contain the products of the corresponding elements from `df1` and `df2`.

6). What is the output of the following code?

				
					import pandas as pd
df1 = pd.Series([1,6,9,5])
df2 = pd.Series([5,2,4,5])
print(df1/df2)
				
			

a) 0 0.2
1 3.0
2 2.25
3 1.0
dtype: float64

b) 0 0.2
1 3.0
2 2.25
3 5.0
dtype: float64

c) 0 5.0
1 3.0
2 2.25
3 5.0
dtype: float64

d) 0 0.2
1 6.0
2 2.25
3 1.0
dtype: float64

Correct answer is: a
Explanation: When dividing two Series (`df1` and `df2`), Pandas perform element-wise division. The resulting Series will have the same indices as the original Series.

7). What is the output of the following code?

				
					import pandas as pd
df1 = pd.Series([1, 6, 9, 5])
df2 = pd.Series([5, 2, 4, 5])
print("Equals:")
print(df1 == df2)
				
			

a) Equals:
0 False
1 False
2 False
3 True
dtype: bool

b) Equals:
0 False
1 True
2 False
3 True
dtype: bool

c) Equals:
0 True
1 False
2 False
3 True
dtype: bool

d) Equals:
0 False
1 False
2 True
3 False
dtype: bool

Correct answer is: a) Equals:
0 False
1 False
2 False
3 True
dtype: bool
Explanation: The code compares each element of `df1` with the corresponding element of `df2` and returns a boolean Series indicating whether each pair of elements is equal or not. In this case, the output shows that the first three pairs are not equal (`False`), while the last pair is equal (`True`).

8). What is the output of the following code?

				
					import pandas as pd
df1 = pd.Series([1, 6, 9, 5])
df2 = pd.Series([5, 2, 4, 5])
print("Greater than:")
print(df1 > df2)
				
			

a) Greater than:
0 False
1 True
2 True
3 False
dtype: bool

b) Greater than:
0 True
1 False
2 True
3 False
dtype: bool

c) Greater than:
0 False
1 False
2 True
3 False
dtype: bool

d) Greater than:
0 True
1 True
2 False
3 False
dtype: bool

Correct answer is: a) Greater than:
0 False
1 True
2 True
3 False
dtype: bool
Explanation: The code compares the elements of `df1` and `df2` element-wise using the `>` operator. In the output, each element represents the result of the comparison between the corresponding elements of `df1` and `df2`. If an element in `df1` is greater than the corresponding element in `df2`, the result will be `True`, otherwise `False`. In this case, the first element is not greater (False), the second and third elements are greater (True), and the fourth element is not greater (False).

9). What is the output of the following code?

				
					import pandas as pd
D = {'name':'Virat','sport':'cricket','age':32}
result = pd.Series(D)
print(result)
				
			

a)
name Virat
sport cricket
age 32
dtype: object

b)
0 Virat
1 cricket
2 32
dtype: object

c) {‘name’:’Virat’,’sport’:’cricket’,’age’:32}

d)
name cricket
sport Virat
age 32
dtype: object

Correct answer is: a)
name Virat
sport cricket
age 32
dtype: object
Explanation: The code creates a dictionary `D` with three key-value pairs representing a person’s name, sport, and age. It then converts the dictionary into a Pandas Series using `pd.Series(D)`. The resulting Series, `result`, will have the keys of the dictionary as the index labels and the corresponding values as the data)

10). What is the output of the following code?

				
					import numpy as np
import pandas as pd

array = np.array([5, 3, 8, 9, 0])
result = pd.Series(array)
print(result)

				
			

a) 5 3 8 9 0
b) 0 9 8 3 5
c) [5, 3, 8, 9, 0]
d) It will raise an error.

Correct answer is: c) [5, 3, 8, 9, 0]
Explanation: The code creates a NumPy array `array` with values [5, 3, 8, 9, 0]. Then, it creates a Pandas Series `result` from the array. Finally, it prints the Series `result`. The output of the code is a Pandas Series object represented as [5, 3, 8, 9, 0]. The values from the NumPy array are preserved in the Series.

11). What is the output of the following code?

				
					import pandas as pd
df1 = pd.Series([54, 27.90, 'sqa', 33.33, 'tools'])
print("Original Data Series:")
print(df1)
print("Change the said data type to numeric:")
df2 = pd.to_numeric(df1, errors='coerce')
print(df2)
				
			

a) Original Data Series:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object
Change the said data type to numeric:
0 54.00
1 27.90
2 NaN
3 33.33
4 NaN
dtype: float64

b) Original Data Series:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object
Change the said data type to numeric:
0 54
1 27.9
2 NaN
3 33.33
4 NaN
dtype: float64

c) Original Data Series:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object
Change the said data type to numeric:
0 54.00
1 27.90
2 sqa
3 33.33
4 tools
dtype: object

d) Original Data Series:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object
Change the said data type to numeric:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object

Correct answer is: a) Original Data Series:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object
Change the said data type to numeric:
0 54.00
1 27.90
2 NaN
3 33.33
4 NaN
dtype: float64
Explanation: The code first creates a Series `df1` with a mix of integer, float, and string values. Then it prints the original data series. After that, it uses the `pd.to_numeric()` function to convert the data type of `df1` to numeric) The `errors=’coerce’` parameter is used to convert non-numeric values to NaN (Not a Number) instead of raising an error. The resulting converted Series is stored in `df2`. Finally, it prints the converted Series `df2`.

12). What is the output of the following code?

				
					import numpy as np
import pandas as pd

df1 = pd.Series([54, 27.90, 'sqa', 33.33, 'tools'])
print("Original Data Series:")
print(df1)
print("Series to an array")
result = np.array(df1.values.tolist())
print(result)
				
			

a) [54, 27.9, ‘sqa’, 33.33, ‘tools’]
d) [54, 27.9, 33.33]
c) [’54’, ‘27.9’, ‘sqa’, ‘33.33’, ‘tools’]
d) Error: cannot convert ‘sqa’ and ‘tools’ to float

Correct answer is: a) [54, 27.9, ‘sqa’, 33.33, ‘tools’]
Explanation: The code creates a Pandas Series (`df1`) with values [54, 27.90, ‘sqa’, 33.33, ‘tools’]. It then converts the Series into a NumPy array using `np.array(df1.values.tolist())`. The resulting array contains all the values from the Series, including the numeric values and the string values. Therefore, the output of the code is [54, 27.9, ‘sqa’, 33.33, ‘tools’].

13). What is the output of the following code?

				
					import pandas as pd
a = [['Sqa', 'tool'], ['Learning', 'python'], ['Is', 'fun']]
result = pd.Series(a)
print(result)
				
			

a)
0 [Sqa, tool]
1 [Learning, python]
2 [Is, fun]
dtype: object

d)
0 Sqa tool
1 Learning python
2 Is fun
dtype: object

c)
0 Sqa
1 Learning
2 Is
dtype: object

0 tool
1 python
2 fun
dtype: object

d)
0 Sqa Learning Is
1 tool python fun
dtype: object

Correct answer is: a)
0 [Sqa, tool]
1 [Learning, python]
2 [Is, fun]
dtype: object
Explanation: The code creates a Pandas Series object `result` from the list `a`. Each element in the list becomes a separate entry in the Series. Since each element of `a` is a list itself, the output shows the list elements as individual entries in the Series, resulting in a Series with three rows and two columns. The output displays the Series with the index labels and the corresponding values.

14). What is the output of the following code?

				
					import pandas as pd
df = pd.Series([55, 23, 10, 87])
print("Original Data Series:")
print(df)
new = pd.Series(df).sort_values()
print(new)
				
			

a) Original Data Series:
0 55
1 23
2 10
3 87
dtype: int64
2 10
1 23
0 87
3 55
dtype: int64

b) Original Data Series:
55
23
10
87
dtype: int64
10
23
55
87
dtype: int64

c) Original Data Series:
0 55
1 23
2 10
3 87
dtype: int64
3 87
2 10
1 23
0 55
dtype: int64

d) Original Data Series:
55
23
10
87
dtype: int64
87
10
55
23
dtype: int64

Correct answer is: b) Original Data Series:
55
23
10
87
dtype: int64
10
23
55
87
dtype: int64
Explanation: The code first creates a Series `df` with values [55, 23, 10, 87]. It then prints the original data series. Next, it creates a new Series `new` by sorting the values of `df` in ascending order.

15). What is the output of the following code?

				
					import pandas as pd
df = pd.Series([54,27.9,'sqa',33.33,'tools'])
print("Original Data Series:")
print(df)
print("Data Series after adding some data:")
new = df.append(pd.Series(['python',100]))
print(new)
				
			

0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object

Data Series after adding some data:
0 54
1 27.9
2 sqa
3 33.33
4 tools
5 python
6 100
dtype: object

b) Original Data Series:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object

Data Series after adding some data:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object

c) Original Data Series:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object

Data Series after adding some data:
0 54
1 27.9
2 sqa
3 33.33
4 tools
5 python
dtype: int64

d) Original Data Series:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object

Data Series after adding some data:
0 54
1 27.9
2 sqa
3 33.33
4 python
5 100
dtype: float64

Correct answer is: a) Original Data Series:
0 54
1 27.9
2 sqa
3 33.33
4 tools
dtype: object
Data Series after adding some data:
0 54
1 27.9
2 sqa
3 33.33
4 tools
5 python
6 100
dtype: object
Explanation: The code initializes a Pandas Series named `df` with values `[54, 27.9, ‘sqa’, 33.33, ‘tools’]`. It then prints the original data series, which displays the values in the series. Next, the code appends a new Pandas Series to the existing `df` series using the `append()` function. The new series contains the values `[‘python’, 100]`. The appended series is assigned to the variable `new`. Finally, the code prints the modified data series `new`, which includes the original values as well as the appended values. The output displays the combined series with values `[54, 27.9, ‘sqa’, 33.33, ‘tools’, ‘python’, 100]`. The dtype is ‘object’ because the series contains mixed data types.

16). What is the output of the following code?

				
					import pandas as pd
df = pd.Series([10, 25, 69, 74, 33, 54, 21])
print(df)
print("Subset of the above Data Series:")
new = df[df < 40]
print(new)
				
			

a)
0 10
1 25
2 69
3 74
4 33
5 54
6 21
dtype: int64
Subset of the above Data Series:
0 10
1 25
4 33
6 21
dtype: int64

b)
10
25
69
74
33
54
21
Subset of the above Data Series:
10
25
33
21

c)
10
25
69
74
33
54
21
Subset of the above Data Series:
10
25
33

d)
0 10
1 25
2 69
3 74
4 33
5 54
6 21
dtype: int64
Subset of the above Data Series:
33
21

Correct answer is: a)
0 10
1 25
2 69
3 74
4 33
5 54
6 21
dtype: int64
Subset of the above Data Series:
0 10
1 25
4 33
6 21
dtype: int64
Explanation: The code begins by importing the Pandas library and creating a Series called `df` with the values [10, 25, 69, 74, 33, 54, 21]. This shows the index and corresponding values of the `df` Series. Next, the statement `print(“Subset of the above Data Series:”)` is executed, which simply prints the given text. Then, a new Series called `new` is created by selecting the elements from `df` where the value is less than 40 (`df[df < 40]`). The resulting `new` Series contains the values [10, 25, 33, 21].

17). What is the output of the following code?

				
					import pandas as pd
df = pd.Series([5, 4, 8, 6])
print(df)
print("Mean of the given series: ", df.mean())
				
			

a)
0 5
1 4
2 8
3 6
dtype: int64
Mean of the given series: 5.75

b)
5 0
4 1
8 2
6 3
dtype: int64
Mean of the given series: 5.75

c)
0 5
1 4
2 8
3 6
dtype: int64
Mean of the given series: 5.5

d)
5 0
4 1
8 2
6 3
dtype: int64
Mean of the given series: 5.5

Correct answer is: a)
0 5
1 4
2 8
3 6
dtype: int64
Mean of the given series: 5.75
Explanation: The code first creates a Pandas Series object `df` with the values [5, 4, 8, 6]. When printed, the output shows the series with index labels and corresponding values. The mean of the series is calculated using the `mean()` function, which returns the average value of the series. In this case, the mean is 5.75.

18). What is the output of the following code?

				
					import pandas as pd
df = pd.Series([2, 4, 6, 8, 10])
print(df)
print("Standard deviation of the given series: ", df.std())

				
			

a)
0 2
1 4
2 6
3 8
4 10
dtype: int64
Standard deviation of the given series: 2.8284271247461903

b)
2 0
4 1
6 2
8 3
10 4
dtype: int64
Standard deviation of the given series: 3.1622776601683795

c)
2 0
4 0
6 0
8 0
10 0
dtype: int64
Standard deviation of the given series: 4.47213595499958

d)
0 2
1 4
2 6
3 8
4 10
dtype: int64
Standard deviation of the given series: 3.1622776601683795

Correct answer is: d)
0 2
1 4
2 6
3 8
4 10
dtype: int64
Standard deviation of the given series: 3.1622776601683795
Explanation: The code creates a Pandas Series `df` with values [2, 4, 6, 8, 10]. When printing `df`, it displays the series with index labels and corresponding values. The `df.std()` calculates the standard deviation of the given series, which is 3.1622776601683795. This value is printed along with the string “Standard deviation of the given series: “.

19). What is the output of the following code?

				
					import pandas as pd
df1 = pd.Series([4, 7, 3, 10])
df2 = pd.Series([9, 4, 3])
print("First series: \n", df1)
print("Second series: \n", df2)
result = df1[~df1.isin(df2)]
print(result)
				
			

a) 7, 10
b) 9, 4, 3
c) 3, 7, 10
d) 4, 7, 3, 10

Correct answer is: a) 7, 10
Explanation: The given code first creates two Series objects, `df1` and `df2`, with values [4, 7, 3, 10] and [9, 4, 3] respectively. Then, it prints the contents of both Series using the `print()` function. Next, the code assigns to the variable `result` the values from `df1` that are not present in `df2` using the `~` operator and the `isin()` method) In this case, `~df1.isin(df2)` checks which values in `df1` are not found in `df2`. The resulting Boolean Series is then used to filter `df1`, storing only the values that are not present in `df2` in the variable `result`. Finally, the code prints the contents of `result`.

20). What is the output of the following code?

				
					import pandas as pd
df = pd.Series([54, 38, 67, 87])
print(df)
print("Maximum value: ", df.max())

				
			

a)
0 54
1 38
2 67
3 87
dtype: int64
Maximum value: 87

b)
54 0
38 1
67 2
87 3
dtype: int64
Maximum value: 87

c)
0 54
1 38
2 67
3 87
dtype: int64
Maximum value: 3

d)
54
Maximum value: 87

Correct answer is: a)
0 54
1 38
2 67
3 87
dtype: int64
Maximum value: 87
Explanation: The given code first creates a Pandas Series object named `df` with values [54, 38, 67, 87]. When the `print(df)` statement is executed, it displays the Series object with the index and corresponding values. This shows the index (0, 1, 2, 3) and the corresponding values (54, 38, 67, 87) in the Series. Next, the `print(“Maximum value: “, df.max())` statement is executed) It calculates the maximum value in the Series using the `max()` function and displays it along with the specified text.

21). What is the output of the following code?

				
					import pandas as pd
df = pd.Series([54, 38, 67, 87])
print("Minimum value: ", df.min())
				
			

a) Minimum value: 54
b) Minimum value: 38
c) Minimum value: 67
d) Minimum value: 87

Correct answer is: b) Minimum value: 38
Explanation: The code creates a Pandas Series called `df` with the values [54, 38, 67, 87]. The `min()` function is then applied to the Series, which returns the minimum value from the Series. In this case, the minimum value is 38. The print statement displays the output as “Minimum value: 38”. Therefore, option b is the correct answer.

22). What is the output of the following code?

				
					import pandas as pd
df = pd.Series([3, 0, 3, 2, 2, 0, 3, 3, 2])
result = df.value_counts()
print(result)
				
			

a) 0 2
2 3
3 4
dtype: int64
b) 0 3
2 3
3 3
dtype: int64
c) 0 2
2 2
3 3
dtype: int64
d) 0 3
2 2
3 4
dtype: int64

Correct answer is: a) 0 2
2 3
3 4
dtype: int64
Explanation: The code creates a Pandas Series `df` with a list of values. The `value_counts()` function is then applied to the Series to count the occurrences of each unique value. The resulting output is a new Series object `result` that contains the counts of each unique value in the original Series. In this case, the unique values in `df` are [3, 0, 2]. The counts of these values are 4 for 3, 2 for 0, and 3 for 2.

23). What is the output of the following code?

				
					import pandas as pd

df = pd.Series([3, 0, 3, 2, 2, 0, 3, 3, 2])
positions = [1, 4, 7]
result = df.take(positions)
print("Extract items at given positions of the said series:")
print(result)
				
			

a) 0, 2, 3
b) 0, 2, 2
c) 0, 2, 3, 3
d) 0, 3, 3

Correct answer is: a) 0, 2, 3
Explanation: In the given code, the `take()` function is used to extract items at the specified positions from the `df` Series. The positions `[1, 4, 7]` correspond to the elements at index 1, 4, and 7 in the Series. Therefore, the output of `print(result)` will be `0, 2, 3`.

24). What is the output of the following code?

				
					import pandas as pd
df = pd.Series(['sqatools', 'python', 'data', 'science'])
result = df.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper())
print("First and last character of each word to upper case:")
print(result)
				
			

a) `[‘SqaToolS’, ‘PythoN’, ‘DatA’, ‘SciencE’]`
d) `[‘SqatoolS’, ‘Python’, ‘DatA’, ‘SciencE’]`
c) `[‘SqaTools’, ‘PythoN’, ‘Data’, ‘Science’]`
d) `[‘sqatoolS’, ‘PythoN’, ‘Data’, ‘SciencE’]`

Correct answer is: a) `[‘SqaToolS’, ‘PythoN’, ‘DatA’, ‘SciencE’]`
Explanation: The lambda function applied to each element of the Series `df` extracts the first character of each word and converts it to uppercase using `x[0].upper()`. It then appends the middle characters `x[1:-1]` as they are, and finally converts the last character to uppercase using `x[-1].upper()`. The resulting Series `result` contains the modified strings with the first and last character of each word in uppercase. The output of the code will be `[‘SqaToolS’, ‘PythoN’, ‘DatA’, ‘SciencE’]`.

25). What is the output of the following code?

				
					import pandas as pd
df = pd.Series(['virat', 'rohit', 'pant', 'shikhar'])
result = df.map(lambda x: len(x))
print("Number of characters in each word of series:")
print(result)
				
			

a) 5, 5, 4, 7
b) 1, 1, 1, 1
c) 4, 5, 4, 7
d) 0, 0, 0, 0

Correct answer is: a) 5, 5, 4, 7
Explanation: The code creates a Pandas Ser

Python Pandas MCQ : Set 3

Python Pandas MCQ

1). What is the purpose of the `value_counts()` function in Pandas?

a) To calculate the cumulative sum of a column
b) To count the occurrences of each unique value in a column
c) To sort a DataFrame based on a specific column
d) To remove duplicate rows from a DataFrame

Correct answer is: b) To count the occurrences of each unique value in a column
Explanation: The `value_counts()` function in Pandas is used to count the occurrences of each unique value in a column.

2). How can you calculate the difference between two dates in Pandas?

a) df.diff_dates()
b) df.difference()
c) df.calculate_difference()
d) df.subtract_dates()

Correct answer is: a) df.diff_dates()
Explanation: The `diff_dates()` function is used to calculate the difference between two dates in Pandas.

3). What is the purpose of the `fillna()` function in Pandas?

a) To remove missing values from a DataFrame
b) To replace missing values with a specified value
c) To interpolate missing values in a DataFrame
d) To drop rows with missing values

Correct answer is: b) To replace missing values with a specified value
Explanation: The `fillna()` function is used to replace missing values in a DataFrame with a specified value in Pandas.

4). How can you calculate the median of each column in a DataFrame in Pandas?

a) df.median()
b) df.calculate_median()
c) df.column_median()
d) df.median_column()

Correct answer is: a) df.median()
Explanation: The `median()` function in Pandas is used to calculate the median of each column in a DataFrame.

5). What is the purpose of the `rename()` function in Pandas?

a) To calculate the mean of each column in a DataFrame
b) To remove duplicate rows from a DataFrame
c) To change the index labels of a DataFrame
d) To sort a DataFrame based on a specific column

Correct answer is: c) To change the index labels of a DataFrame
Explanation: The `rename()` function in Pandas is used to change the index labels of a DataFrame.

6). How can you calculate the mode of each column in a DataFrame in Pandas?

a) df.mode()
b) df.calculate_mode()
c) df.column_mode()
d) df.mode_column()

Correct answer is: a) df.mode()
Explanation: Each column in a DataFrame’s mode is determined using the Pandas’mode()’ function.

7). What is the purpose of the `cumprod()` function in Pandas?

a) To calculate the cumulative sum of a column
b) To calculate the cumulative product of a column
c) To calculate the cumulative mean of a column
d) To calculate the cumulative median of a column

Correct answer is: b) To calculate the cumulative product of a column
Explanation: The `cumprod()` function in Pandas is used to calculate the cumulative product of a column.

8). How can you calculate the maximum value of each column in a DataFrame in Pandas?

a) df.max()
b) df.maximum()
c) df.calculate_max()
d) df.column_max()

Correct answer is: a) df.max()
Explanation: The `max()` function in Pandas is used to calculate the maximum value of each column in a DataFrame.

9). What is the purpose of the `cummin()` function in Pandas?

a) To calculate the cumulative sum of a column
b) To calculate the cumulative minimum of a column
c) To calculate the cumulative mean of a column
d) To calculate the cumulative median of a column

Correct answer is: b) To calculate the cumulative minimum of a column
Explanation: The `cummin()` function in Pandas is used to calculate the cumulative minimum of a column.

10). How can you calculate the minimum value of each column in a DataFrame in Pandas?

a) df.min()
b) df.minimum()
c) df.calculate_min()
d) df.column_min()

Correct answer is: a) df.min()
Explanation: The `min()` function in Pandas is used to calculate the minimum value of each column in a DataFrame.

11). How can you select multiple columns from a DataFrame in Pandas?

a) df.select_columns()
b) df.columns()
c) df.get_columns()
d) df[[‘column1’, ‘column2’]]

Correct answer is: d) df[[‘column1’, ‘column2’]]
Explanation: To select multiple columns from a DataFrame in Pandas, you can use the double square bracket notation.

12). How can you calculate the standard deviation of each column in a DataFrame in Pandas?

a) df.std()
b) df.standard_deviation()
c) df.calculate_std()
d) df.column_std()

Correct answer is: a) df.std()
Explanation: The `std()` function in Pandas is used to calculate the standard deviation of each column in a DataFrame.

13). What is the purpose of the `agg()` function in Pandas?

a) To aggregate data based on a specific column
b) To determine a column’s average value
c) To remove rows with empty values
d) To sort a DataFrame based on a specific column

Correct answer is: a) To aggregate data based on a specific column
Explanation: The `agg()` function in Pandas is used to aggregate data based on a specific column using a specified function or a dictionary of functions.

14). How can you calculate the skewness of each column in a DataFrame in Pandas?

a) df.skew()
b) df.calculate_skewness()
c) df.column_skewness()
d) df.skewness()

Correct answer is: a) df.skew()
Explanation: The `skew()` function in Pandas is used to calculate the skewness of each column in a DataFrame.

15). How can you calculate the kurtosis of each column in a DataFrame in Pandas?

a) df.kurtosis()
b) df.calculate_kurtosis()
c) df.column_kurtosis()
d) df.kurt()

Correct answer is: a) df.kurtosis()
Explanation: The `kurtosis()` function in Pandas is used to calculate the kurtosis of each column in a DataFrame.

16). What is the purpose of the `iterrows()` function in Pandas?

a) To iterate over the rows of a DataFrame
b) To iterate over the columns of a DataFrame
c) To iterate over the unique values of a column
d) To iterate over the index labels of a DataFrame

Correct answer is: a) To iterate over the rows of a DataFrame
Explanation: The `iterrows()` function in Pandas is used to iterate over the rows of a DataFrame.

17). How can you calculate the covariance between two columns in a DataFrame in Pandas?

a) df.calculate_covariance()
b) df.column_covariance()
c) df.cov()
d) df.covariance()

Correct answer is: c) df.cov()
Explanation: The `cov()` function in Pandas is used to calculate the covariance between two columns in a DataFrame.

18). What is the purpose of the `pivot()` function in Pandas?

a) To transpose the rows and columns of a DataFrame
b) To calculate the average value of a column in a DataFrame
c) To create a summary table based on a DataFrame’s columns
d) To reshape the structure of a DataFrame

Correct answer is: d) To reshape the structure of a DataFrame
Explanation: The `pivot()` function in Pandas is used to reshape the structure of a DataFrame based on the values of a column.

19). How can you calculate the percentile of each column in a DataFrame in Pandas?

a) df.percentile()
b) df.calculate_percentile()
c) df.column_percentile()
d) df.quantile()

Correct answer is: d) df.quantile()
Explanation: The `quantile()` function in Pandas is used to calculate the percentile of each column in a DataFrame.

20). What is the purpose of the `rolling()` function in Pandas?

a) To calculate rolling statistics on a column
b) To remove duplicate rows from a DataFrame
c) To interpolate missing values in a DataFrame
d) To calculate the cumulative sum of a column

Correct answer is: a) To calculate rolling statistics on a column
Explanation: The `rolling()` function in Pandas is used to calculate rolling statistics, such as the rolling mean or rolling sum, on a column.

21). How can you calculate the exponential moving average of a column in a DataFrame in Pandas?

a) df.calculate_ema()
b) df.ema()
c) df.exp_moving_average()
d) df.ewm()

Correct answer is: d) df.ewm()
Explanation: The `ewm()` function in Pandas is used to calculate the exponential moving average of a column in a DataFrame.

22). What is the purpose of the `stack()` function in Pandas?

a) To stack multiple DataFrames vertically
b) To stack multiple DataFrames horizontally
c) To stack multiple columns into a single column
d) To stack multiple rows into a single row

Correct answer is: c) To stack multiple columns into a single column
Explanation: The `stack()` function in Pandas is used to stack multiple columns into a single column.

23). How can you calculate the weighted average of a column in a DataFrame in Pandas?

a) df.calculate_weighted_average()
b) df.weighted_avg()
c) df.column_weighted_average()
d) df.dot_product()

Correct answer is: b) df.weighted_avg()
Explanation: There is no built-in weighted average function in Pandas. However, you can calculate the weighted average by multiplying the values of a column by their corresponding weights and then dividing the sum by the sum of the weights.

24). What is the purpose of the `squeeze()` function in Pandas?

a) To remove a single-dimensional axis from a DataFrame
b) To compress the data in a DataFrame to reduce memory usage
c) To remove duplicate rows from a DataFrame
d) To sort a DataFrame based on a specific column

Correct answer is: a) To remove a single-dimensional axis from a DataFrame
Explanation: The `squeeze()` function in Pandas is used to remove a single-dimensional axis from a DataFrame, resulting in a Series if applicable.

25). What is the purpose of the melt() function in Pandas?

a) To merge multiple DataFrames based on a common column
b) To transpose the rows and columns of a DataFrame
c) To reshape a DataFrame from wide to long format
d) To calculate the median of each column in a DataFrame

Correct answer is: c) To reshape a DataFrame from wide to long format
Explanation: The melt() function in Pandas is used to reshape a DataFrame from wide to long format by unpivoting the data based on specified columns.

Python Pandas MCQ : Set 2

Python Pandas MCQ 

1). What is the purpose of the `iloc` attribute in Pandas?

a) To access rows and columns of a DataFrame by their index location
b) To access rows and columns of a DataFrame by their label
c) To access rows and columns of a DataFrame by their data type
d) To access rows and columns of a DataFrame randomly

Correct answer is: a) To access rows and columns of a DataFrame by their index location
Explanation: The `iloc` attribute in Pandas is used to access rows and columns of a DataFrame by their index location (integer position).

2). How can you calculate the correlation between columns in a DataFrame in Pandas?

a) df.corr()
b) df.correlation()
c) df.calculate_correlation()
d) df.stats.correlation()

Correct answer is: a) df.corr()
Explanation: The correlation between columns in a DataFrame is determined using the ‘corr()’ function in the Pandas programming language.

3). What is the purpose of the `dtypes` attribute in Pandas?

a) To calculate descriptive statistics of a DataFrame
b) To access the data types of each column in a DataFrame
c) To convert the data types of a DataFrame
d) To filter rows based on a condition

Correct answer is: b) To access the data types of each column in a DataFrame
Explanation: The `dtypes` attribute in Pandas is used to access the data types of each column in a DataFrame.

4). How can you apply a filter to a DataFrame based on multiple conditions in Pandas?

a) df.filter(condition1, condition2)
b) df.where(condition1, condition2)
c) df.loc[condition1, condition2]
d) df.apply(condition1, condition2)

Correct answer is: c) df.loc[condition1, condition2]
Explanation: You can apply a filter to a DataFrame based on multiple conditions using the `df.loc[condition1, condition2]` syntax in Pandas.

5). What is the purpose of the `to_datetime()` function in Pandas?

a) To convert a DataFrame to a datetime format
b) To convert a string to a datetime object
c) To calculate the difference between two datetime objects
d) To extract specific components from a datetime object

Correct answer is: b) To convert a string to a datetime object
Explanation: The `to_datetime()` function in Pandas is used to convert a string to a datetime object, enabling date and time operations.

6). How can you resample time series data in Pandas?

a) df.resample()
b) df.time_resample()
c) df.sample_time()
d) df.time_sample()

Correct answer is: a) df.resample()
Explanation: The `resample()` function in Pandas is used to resample time series data, such as converting daily data to monthly data)

7). What is the purpose of the `shift()` function in Pandas?

a) To shift the index labels of a DataFrame
b) To shift the values in a DataFrame by a specified number of periods
c) To shift the columns of a DataFrame
d) To shift the rows of a DataFrame

Correct answer is: b) To shift the values in a DataFrame by a specified number of periods
Explanation: To move the values in a DataFrame by a defined number of periods, use Pandas’ “shift()” function.

8). How can you apply a function to groups in a DataFrame in Pandas?

a) df.groupby().apply()
b) df.group().apply()
c) df.group_by().apply()
d) df.groupby().function()

Correct answer is: a) df.groupby().apply()
Explanation: You can apply a function to groups in a DataFrame using the `groupby().apply()` syntax in Pandas.

9). What is the purpose of the `duplicated()` function in Pandas?

a) To remove duplicate rows from a DataFrame
b) To identify duplicate values in a DataFrame
c) To drop rows with missing values
d) To sort a DataFrame based on a specific column

Correct answer is: b) To identify duplicate values in a DataFrame
Explanation: The `duplicated()` function in Pandas is used to identify duplicate values in a DataFrame.

10). How can you change the data type of a column in a DataFrame in Pandas?

a) df.change_dtype(column_name, new_type)
b) df.column_name = new_type
c) df.astype(column_name, new_type)
d) df.change_type(column_name, new_type)

Correct answer is: c) df.astype(column_name, new_type)
Explanation: The `astype()` function is used to change the data type of a column in a DataFrame in Pandas.

11). What is the purpose of the `cut()` function in Pandas?

a) To divide a continuous variable into discrete bins
b) To calculate the cumulative sum of a column
c) To transform a categorical variable into numerical codes
d) To create a histogram of a column

Correct answer is: a) To divide a continuous variable into discrete bins
Explanation: The `cut()` function in Pandas is used to divide a continuous variable into discrete bins or intervals.

12). How can you create a new column based on existing columns in a DataFrame in Pandas?

a) df.add_column()
b) df.create_column()
c) df.new_column()
d) df[column_name] = expression

Correct answer is: d) df[column_name] = expression
Explanation: You can create a new column based on existing columns in a DataFrame by assigning a new column name and an expression to it.

13). What is the purpose of the `transform()` function in Pandas?

a) To apply a function to each element in a DataFrame
b) To calculate summary statistics for each group in a DataFrame
c) To transform a column by replacing values based on a condition
d) To reshape the structure of a DataFrame

Correct answer is: b) To calculate summary statistics for each group in a DataFrame
Explanation: The `transform()` function in Pandas is used to calculate summary statistics for each group in a DataFrame.

14). How can you drop duplicate rows from a DataFrame in Pandas?

a) df.drop_duplicates()
b) df.remove_duplicates()
c) df.delete_duplicates()
d) df.drop_rows_duplicates()

Correct answer is: a) df.drop_duplicates()
Explanation: The `drop_duplicates()` method is used to drop duplicate rows from a DataFrame in Pandas.

15). What is the purpose of the `isnull()` function in Pandas?

a) To check if values in a DataFrame are null or missing
b) To remove null or missing values from a DataFrame
c) To replace null or missing values with a specified value
d) To interpolate null or missing values in a DataFrame

Correct answer is: a) To check if values in a DataFrame are null or missing
Explanation: The `isnull()` function in Pandas is used to check if values in a DataFrame are null or missing.

16). How can you calculate the cumulative sum of a column in a DataFrame in Pandas?

a) df.cumulative_sum()
b) df.cumsum()
c) df.sum_cumulative()
d) df.calculate_cumulative()

Correct answer is: b) df.cumsum()
Explanation: The `cumsum()` function is used to calculate the cumulative sum of a column in a DataFrame in Pandas.

17). What is the purpose of the `nunique()` function in Pandas?

a) To count the number of unique values in each column
b) To remove duplicate rows from a DataFrame
c) To calculate the mean of each column
d) To sort a DataFrame based on a specific column

Correct answer is: a) To count the number of unique values in each column
Explanation: The `nunique()` function in Pandas is used to count the number of unique values in each column of a DataFrame.

18). How can you extract specific components from a datetime column in a DataFrame in Pandas?

a) df.extract()
b) df.components()
c) df.dt.component()
d) df.get_component()

Correct answer is: c) df.dt.component()
Explanation: You can extract specific components from a datetime column in a DataFrame using the `dt.component()` syntax in Pandas.

19). What is the purpose of the `sample()` function in Pandas?

a) To randomly shuffle the rows of a DataFrame
b) To select a random sample of rows from a DataFrame
c) To calculate the mean of each column
d) To sort a DataFrame based on a specific column

Correct answer is: b) To select a random sample of rows from a DataFrame
Explanation: The `sample()` function in Pandas is used to select a random sample of rows from a DataFrame.

20). How can you calculate the mean of each column in a DataFrame in Pandas?

a) df.mean()
b) df.calculate_mean()
c) df.column_mean()
d) df.mean_column()

Correct answer is: a) df.mean()
Explanation: The `mean()` function in Pandas is used to calculate the mean of each column in a DataFrame.

21). What is the purpose of the unique() function in Pandas?

a) To calculate the unique values in a column
b) To remove duplicate rows from a DataFrame
c) To count the occurrences of each unique value in a column
d) To sort a DataFrame based on a specific column

Correct answer is: a) To calculate the unique values in a column
Explanation: The unique() function in Pandas is used to calculate the unique values in a column.

22). How can you calculate the sum of each column in a DataFrame in Pandas?

a) df.calculate_sum()
b) df.sum()
c) df.column_sum()
d) df.total()

Correct answer is: b) df.sum()
Explanation: The sum() function in Pandas is used to calculate the sum of each column in a DataFrame.

23). What is the purpose of the dropna() function in Pandas?

a) To calculate descriptive statistics of a DataFrame
b) To remove missing values from a DataFrame
c) To replace missing values with a specified value
d) To interpolate missing values in a DataFrame

Correct answer is: b) To remove missing values from a DataFrame
Explanation: The dropna() function in Pandas is used to remove missing values from a DataFrame.

24). How can you calculate the correlation matrix of a DataFrame in Pandas?

a) df.calculate_correlation()
b) df.correlation_matrix()
c) df.corr()
d) df.matrix_correlation()

Correct answer is: c) df.corr()
Explanation: The corr() function in Pandas is used to calculate the correlation matrix of a DataFrame.

25). How can you calculate the cumulative maximum of each column in a DataFrame in Pandas?

a) df.cumulative_max()
b) df.max_cumulative()
c) df.cummax()
d) df.calculate_max()

Correct answer is: c) df.cummax()
Explanation: The cummax() function in Pandas is used to calculate the cumulative maximum of each column in a DataFrame.

Python Pandas MCQ : Set 1

Python Pandas MCQ

1). What is Pandas?

a) A Python package for data analysis and manipulation
b) A Python framework for web development
c) A Python module for machine learning
d) A Python library for graphical plotting

Correct answer is: a) A Python package for data analysis and manipulation
Explanation: Pandas is a popular Python package used for data analysis and manipulation. It offers data structures and procedures to handle structured data effectively.

2). Which of the following data structures is commonly used in Pandas?

a) Arrays
b) Lists
c) DataFrames
d) Tuples

Correct answer is: c) DataFrames
Explanation: The primary data structure in Pandas is the DataFrame, which is a two-dimensional labeled data structure capable of holding data of different types.

3). How can you install Pandas in Python?

a) Using pip: pip install pandas
b) Using conda: conda install pandas
c) Both a and b
d) Pandas is pre-installed with Python

Correct answer is: c) Both a and b
Explanation: Pandas can be installed using either pip or conda package managers.

4). Which of the following statements is true about Series in Pandas?

a) It is a one-dimensional labeled array
b) It is a two-dimensional labeled array
c) It is a three-dimensional labeled array
d) It is a multi-dimensional labeled array

Correct answer is: a) It is a one-dimensional labeled array
Explanation: A Series is a labelled one-dimensional array that can hold any kind of data.

5). How can you access the first n rows of a DataFrame in Pandas?

a) df.head(n)
b) df.tail(n)
c) df.first(n)
d) df.last(n)

Correct answer is: a) df.head(n)
Explanation: The `head(n)` method in Pandas allows you to access the first n rows of a DataFrame.

6). What is the default index type for a DataFrame in Pandas?

a) Integer index
b) String index
c) Date index
d) Floating-point index

Correct answer is: a) Integer index
Explanation: By default, Pandas assigns an integer index to each row in a DataFrame.

7). How can you drop a column from a DataFrame in Pandas?

a) df.drop(column_name)
b) df.drop(columns=column_name)
c) df.remove(column_name)
d) df.delete(column_name)

Correct answer is: b) df.drop(columns=column_name)
Explanation: The `drop(columns=column_name)` method is used to drop a column from a DataFrame in Pandas.

8). What is the function to calculate the summary statistics of a DataFrame in Pandas?

a) df.summary()
b) df.describe()
c) df.stats()
d) df.statistics()

Correct answer is: b) df.describe()
Explanation: The `describe()` function in Pandas provides summary statistics of a DataFrame, including count, mean, standard deviation, minimum, maximum, and quartiles.

9). How can you filter rows in a DataFrame based on a condition in Pandas?

a) df.filter(condition)
b) df.where(condition)
c) df.select(condition)
d) df.loc[condition]

Correct answer is: d) df.loc[condition]
Explanation: You can filter rows in a DataFrame based on a condition using the `df.loc[condition]` syntax in Pandas.

10). What is the purpose of the `fillna()` function in Pandas?

a) To remove missing values from a DataFrame
b) To replace missing values with a specified value
c) To interpolate missing values in a DataFrame
d) To drop rows with missing values

Correct answer is: b) To replace missing values with a specified value
Explanation: The `fillna()` function is used to replace missing values in a DataFrame with a specified value in Pandas.

11). How can you sort a DataFrame by a specific column in Pandas?

a) df.sort(column_name)
b) df.sort_by(column_name)
c) df.sort_values(by=column_name)
d) df.order_by(column_name)

Correct answer is: c) df.sort_values(by=column_name)
Explanation: The `sort_values(by=column_name)` method is used to sort a DataFrame by a specific column in Pandas.

12). What is the purpose of the `groupby()` function in Pandas?

a) To filter rows based on a condition
b) To combine rows based on a specific column
c) To calculate summary statistics for each group
d) To sort the DataFrame in ascending order

Correct answer is: b) To combine rows based on a specific column
Explanation: The `groupby()` function in Pandas is used to combine rows based on a specific column, creating groups of related data)

13). How can you apply a function to each element in a DataFrame in Pandas?

a) df.apply()
b) df.map()
c) df.transform()
d) df.iterate()

Correct answer is: a) df.apply()
Explanation: The `apply()` function in Pandas is used to apply a function to each element in a DataFrame.

14). What is the purpose of the `merge()` function in Pandas?

a) To remove duplicate rows from a DataFrame
b) To combine two DataFrames based on a common column
c) To calculate the correlation between columns in a DataFrame
d) To reshape the structure of a DataFrame

Correct answer is: b) To combine two DataFrames based on a common column
Explanation: The `merge()` function in Pandas is used to combine two DataFrames based on a common column, similar to the SQL join operation.

15). What is the purpose of the `pivot_table()` function in Pandas?

a) To transpose the rows and columns of a DataFrame
b) To calculate the average value of a column in a DataFrame
c) To create a summary table based on a DataFrame’s columns
d) To reshape the structure of a DataFrame

Correct answer is: c) To create a summary table based on a DataFrame’s columns
Explanation: The `pivot_table()` function in Pandas is used to create a summary table based on a DataFrame’s columns, similar to Excel’s PivotTable functionality.

16). How can you save a DataFrame to a CSV file in Pandas?

a) df.to_csv(filename)
b) df.save_csv(filename)
c) df.write_csv(filename)
d) df.export_csv(filename)

Correct answer is: a) df.to_csv(filename)
Explanation: The `to_csv(filename)` method is used to save a DataFrame to a CSV file in Pandas.

17). What is the purpose of the `read_csv()` function in Pandas?

a) To read data from a CSV file into a DataFrame
b) To export a DataFrame to a CSV file
c) To calculate summary statistics for a DataFrame
d) To sort a DataFrame based on a specific column

Correct answer is: a) To read data from a CSV file into a DataFrame
Explanation: The `read_csv()` function in Pandas is used to read data from a CSV file and create a DataFrame.

18). How can you handle missing values in a DataFrame in Pandas?

a) df.dropna()
b) df.fillna(value)
c) df.interpolate()
d) All of the above

Correct answer is: d) All of the above
Explanation: You can handle missing values in a DataFrame in Pandas by dropping them using `dropna()`, filling them with a specified value using `fillna(value)`, or interpolating them using `interpolate()`.

19). What is the purpose of the `datetime` module in Pandas?

a) To perform date and time calculations
b) To format dates and times in a DataFrame
c) To parse date and time strings into a DataFrame
d) To figure out how much time has passed between two dates

Correct answer is: a) To perform date and time calculations
Explanation: The `datetime` module in Pandas provides functions and classes to work with dates and times, perform calculations, and handle time-related operations.

20). How can you rename the columns of a DataFrame in Pandas?

a) df.rename(columns=new_columns)
b) df.columns = new_columns
c) df.relabel(columns=new_columns)
d) df.change_columns(new_columns)

Correct answer is: a) df.rename(columns=new_columns)
Explanation: The `rename(columns=new_columns)` method is used to rename the columns of a DataFrame in Pandas.

21). What is the purpose of the pivot() function in Pandas?

a) To transpose the rows and columns of a DataFrame
b) To calculate the average value of a column in a DataFrame
c) To create a summary table based on a DataFrame’s columns
d) To reshape the structure of a DataFrame

Correct answer is: d) To reshape the structure of a DataFrame
Explanation: The pivot() function in Pandas is used to reshape the structure of a DataFrame based on the values of a column.

22). How can you convert a DataFrame into a NumPy array in Pandas?

a) df.to_array()
b) df.to_numpy()
c) df.convert_array()
d) df.as_numpy()

Correct answer is: b) df.to_numpy()
Explanation: The to_numpy() method is used to convert a DataFrame into a NumPy array in Pandas.

23). What is the purpose of the corr() function in Pandas?

a) To calculate the correlation between columns in a DataFrame
b) To calculate the covariance between columns in a DataFrame
c) To calculate the cumulative sum of a column
d) To calculate the mean of each column

Correct answer is: a) To calculate the correlation between columns in a DataFrame
Explanation: The corr() function in Pandas is used to calculate the correlation between columns in a DataFrame.

24). How can you calculate the cross-tabulation between two columns in a DataFrame in Pandas?

a) df.cross_tab()
b) df.crosstab()
c) df.tabulate()
d) df.pivot_table()

Correct answer is: b) df.crosstab()
Explanation: The crosstab() function is used to calculate the cross-tabulation between two columns in a DataFrame in Pandas.

25). What is the purpose of the rank() function in Pandas?

a) To calculate the rank of values within a column
b) To remove duplicate rows from a DataFrame
c) To determine each column’s mean
d) To sort a DataFrame based on a specific column

Correct answer is: a) To calculate the rank of values within a column
Explanation: The rank() function in Pandas is used to calculate the rank of values within a column.

Python OOPS MCQ : Set 4

Python OOPS MCQ

1). What is the output of the following code?

				
					class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
    
    def calculate_area(self):
        return self.length * self.width
    
    def calculate_perimeter(self):
        return 2 * (self.length + self.width)

# Create an object of the Rectangle class
rectangle = Rectangle(5, 13)
area = rectangle.calculate_area()
perimeter = rectangle.calculate_perimeter()
print("Area:", area)
print("Perimeter:", perimeter)
				
			

a) Area: 65, Perimeter: 54
b) Area: 65, Perimeter: 36
c) Area: 18, Perimeter: 26
d) Area: 18, Perimeter: 36

Correct answer is: b) Area: 65, Perimeter: 36
Explanation: The code defines a `Rectangle` class with an `__init__` method to initialize the `length` and `width` attributes. It also has two additional methods, `calculate_area()` and `calculate_perimeter()`, which calculate the area and perimeter of the rectangle, respectively. In the code, an object `rectangle` is created using the `Rectangle` class with `length=5` and `width=13`. The `calculate_area()` method is called on the `rectangle` object and the result is assigned to the `area` variable. Similarly, the `calculate_perimeter()` method is called and the result is assigned to the `perimeter` variable. Finally, the values of `area` and `perimeter` are printed to the console.

2). What is the output of the following code?

				
					import math
class Circle:
    def __init__(self, radius):
        self.radius = radius
    
    def calculate_area(self):
        return math.pi * self.radius**2
    
    def calculate_circumference(self):
        return 2 * math.pi * self.radius

# Create an object of the Circle class
circle = Circle(10)
area = circle.calculate_area()
circumference = circle.calculate_circumference()
print("Area:", area)
print("Circumference:", circumference)
				
			

a) Area: 314.1592653589793 Circumference: 62.83185307179586
b) Area: 314.1592653589793 Circumference: 31.41592653589793
c) Area: 628.3185307179587 Circumference: 31.41592653589793
d) Area: 628.3185307179587 Circumference: 62.83185307179586

Correct answer is: a) Area: 314.1592653589793 Circumference: 62.83185307179586
Explanation: In the given code, a Circle class is defined with an `__init__` method to initialize the radius attribute. It also has two methods, `calculate_area` and `calculate_circumference`, to calculate the area and circumference of the circle, respectively. An object `circle` is created with a radius of 10. The `calculate_area` method is called on the `circle` object, which returns the area of the circle using the formula `math.pi * self.radius**2`. Similarly, the `calculate_circumference` method is called, which returns the circumference of the circle using the formula `2 * math.pi * self.radius`. Finally, the calculated area and circumference are printed using the `print` function.

3). What is the output of the following code?

				
					class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def print_details(self):
        print("Name:", self.name)
        print("Age:", self.age)

# Create an object of the Person class
person = Person("John Snow", 28)
person.print_details()
				
			

a) Name: John Snow, Age: 28
b) Name: John Snow, Age: None
c) Name: None, Age: 28
d) Error: missing arguments for __init__ method

Correct answer is: a) Name: John Snow, Age: 28
Explanation: In the given code, a class `Person` is defined with an `__init__` method to initialize the name and age attributes. The `print_details` method is used to print the name and age of the person. An object `person` is created with the name “John Snow” and age 28. Then, the `print_details` method is called on the `person` object, which prints the name as “John Snow” and the age as 28.

4). What is the output of the following code?

				
					class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def print_details(self):
        print("Name:", self.name)
        print("Age:", self.age)
        
class Student(Person):
    def __init__(self, name, age, student_id, grades):
        super().__init__(name, age)
        self.student_id = student_id
        self.grades = grades
    
    def print_details(self):
        super().print_details()
        print("Student ID:", self.student_id)

# Create an object of the Student class
student = Student("Jade Smith", 24, "A12345", ['A','A+'])
student.print_details()
				
			

a) Name: Jade Smith, Age: 24, Student ID: A12345
b) Name: Jade Smith, Age: 24
c) Name: Jade Smith, Age: 24, Student ID: A12345, Grades: [‘A’,’A+’]
d) This code will raise an error.

Correct answer is: a) Name: Jade Smith, Age: 24, Student ID: A12345
Explanation: The code defines two classes, `Person` and `Student`, where `Student` is a subclass of `Person`. The `Person` class has an `__init__` method that initializes the `name` and `age` attributes, and a `print_details` method that prints the name and age. The `Student` class inherits from `Person` and adds the `student_id` and `grades` attributes. It also overrides the `print_details` method to include printing the student ID. In the code, an object `student` is created with the name “Jade Smith”, age 24, student ID “A12345”, and grades [‘A’,’A+’]. When the `print_details` method is called on the `student` object, it first calls the `print_details` method of the superclass `Person` using `super().print_details()`. This prints the name and age. Then, it prints the student ID using `print(“Student ID:”, self.student_id)`.

5). What is the output of the following code?

				
					class Animal:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    
    def print_details(self):
        print("Name:", self.name)
        print("Color:", self.color)

class Cat(Animal):
    def __init__(self, name, color, breed, weight):
        super().__init__(name, color)
        self.breed = breed
        self.weight = weight
    
    def print_details(self):
        super().print_details()
        print("Breed:", self.breed)
        print("Weight:", self.weight)

# Create an object of the Cat class
cat = Cat("Whiskers", "Gray", "Persian", 15)
cat.print_details()
				
			

a) Name: Whiskers
Color: Gray
Breed: Persian
Weight: 15
b) Name: Whiskers
Breed: Persian
Weight: 15
c) Name: Whiskers
Color: Gray
Breed: Persian
d) Name: Whiskers
Color: Gray
Breed: Persian
Weight: 15
Animal object

Correct answer is: a) Name: Whiskers
Color: Gray
Breed: Persian
Weight: 15
Explanation: The given code defines two classes, `Animal` and `Cat`. The `Cat` class is a subclass of the `Animal` class and overrides the `print_details()` method. In the `__init__()` method of the `Cat` class, the `super()` function is used to call the `__init__()` method of the superclass (`Animal`) and initialize the `name` and `color` attributes. The `print_details()` method of the `Cat` class first calls the `print_details()` method of the superclass using `super().print_details()`. This prints the name and color from the `Animal` class. Then, it prints the breed and weight specific to the `Cat` class.

6). What is the output of the following code?

				
					class BankAccount:
    def __init__(self, account_number, balance):
        self.account_number = account_number
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        print("Deposit of", amount, "successful. New balance:", self.balance)
    
    def withdraw(self, amount):
        if self.balance >= amount:
            self.balance -= amount
            print("Withdrawal of", amount, "successful. New balance:", self.balance)
        else:
            print("Insufficient funds. Withdrawal denied.")

# Create an object of the BankAccount class
account = BankAccount("1234567890", 1000)
account.deposit(500)
account.withdraw(2000)
				
			

a) Deposit of 500 successful. New balance: 1500. Insufficient funds. Withdrawal denied.
b) Deposit of 1500 successful. New balance: 2500. Insufficient funds. Withdrawal denied.
c) Deposit of 1500 successful. New balance: 1500. Withdrawal of 2000 successful. New balance: -500.
d) Deposit of 500 successful. New balance: 1500. Withdrawal of 2000 successful. New balance: -500.

Correct answer is: a) Deposit of 500 successful. New balance: 1500. Insufficient funds. Withdrawal denied.
Explanation: The code defines a `BankAccount` class with an `__init__` method, `deposit` method, and `withdraw` method. An object `account` is created using the `BankAccount` class with an initial balance of 1000. `account.deposit(500)` is called, which increases the balance by 500 and prints “Deposit of 500 successful. New balance: 1500”. `account.withdraw(2000)` is called, which checks if the balance is sufficient. Since the balance is less than the requested withdrawal amount, it prints “Insufficient funds. Withdrawal denied.”

7). What is the output of the following code?

				
					class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
    
    def print_details(self):
        print("Make:", self.make)
        print("Model:", self.model)
        print("Year:", self.year)

# Create an object of the Car class
car = Car("Mahindra", "Thar", 2021)
car.print_details()
				
			

a) Make: Mahindra
Model: Thar
Year: 2021
b) Mahindra
Thar
2021
c) Car
d) Error: Missing argument in the `__init__` method

Correct answer is:
a) Make: Mahindra
Model: Thar
Year: 2021
Explanation: The code defines a `Car` class with an `__init__` method and a `print_details` method. The `__init__` method is used to initialize the attributes `make`, `model`, and `year` of the `Car` object. The `print_details` method prints the values of these attributes. In the code, an object `car` of the `Car` class is created with the arguments “Mahindra”, “Thar”, and 2021. Then, the `print_details` method is called on the `car` object.

8). What is the output of the following code?

				
					class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
    
    def print_details(self):
        print("Make:", self.make)
        print("Model:", self.model)
        print("Year:", self.year)
        
class ElectricCar(Car):
    def __init__(self, make, model, year, battery_size, range_per_charge):
        super().__init__(make, model, year)
        self.battery_size = battery_size
        self.range_per_charge = range_per_charge
    
    def calculate_range(self):
        return self.battery_size * self.range_per_charge

# Create an object of the ElectricCar class
electric_car = ElectricCar("Tesla", "Model S", 2022, 75, 5)
range = electric_car.calculate_range()
print("Range:", range)
				
			

a) Range: 375
b) Make: Tesla, Model: Model S, Year: 2022, Range: 375
c) Range: 150
d) Make: Tesla, Model: Model S, Year: 2022, Range: 150

Correct answer is:
a) Range: 375
Explanation: The code defines two classes, `Car` and `ElectricCar`, where `ElectricCar` is a subclass of `Car`. The `ElectricCar` class has an additional method `calculate_range()` that multiplies the battery size (`75`) with the range per charge (`5`) to calculate the range. In the code, an object `electric_car` of the `ElectricCar` class is created with the parameters “Tesla”, “Model S”, 2022, 75, and 5. The `calculate_range()` method is then called on `electric_car` and the result is stored in the variable `range`. Finally, the value of `range` is printed as “Range: 375”.

9). What is the output of the following code?

				
					class StudentRecord:
    def __init__(self, name, age, grades):
        self.name = name
        self.age = age
        self.grades = grades
    
    def calculate_average_grade(self):
        total_grades = sum(self.grades)
        average_grade = total_grades / len(self.grades)
        return average_grade
    
    def print_details(self):
        print("Name:", self.name)
        print("Age:", self.age)
        print("Average Grade:", self.calculate_average_grade())

# Create an object of the StudentRecord class
student = StudentRecord("John show", 20, [80, 90, 85, 95])
student.print_details()
				
			

a) Name: John show, Age: 20, Average Grade: 87.5
b) Name: John show, Age: 20, Average Grade: 90.0
c) Name: John show, Age: 20, Average Grade: 82.5
d) Name: John show, Age: 20, Average Grade: 92.5

Correct answer is: a) Name: John show, Age: 20, Average Grade: 87.5
Explanation: The code defines a class `StudentRecord` with an `__init__` method, a `calculate_average_grade` method, and a `print_details` method. It then creates an object `student` of the `StudentRecord` class with the name “John show”, age 20, and grades [80, 90, 85, 95]. The `print_details` method is called on the `student` object, which prints the name, age, and average grade. The average grade is calculated by summing the grades and dividing by the number of grades, resulting in 87.5. Therefore, the output of the code will be “Name: John show, Age: 20, Average Grade: 87.5”.

10). What is the output of the following code?

				
					class Course:
    def __init__(self, name, teacher):
        self.name = name
        self.teacher = teacher
        self.students = []
    
    def add_student(self, student):
        self.students.append(student)
    
    def remove_student(self, student):
        if student in self.students:
            self.students.remove(student)
    
    def print_details(self):
        print("Course Name:", self.name)
        print("Teacher:", self.teacher)
        print("Students:")
        for student in self.students:
            print("- ", student)

# Create an object of the Course class
course = Course("Python", "Mr. Dipesh Yadav")
course.add_student("John Walker")
course.add_student("Jade Smith")
course.print_details()
course.remove_student("Jade Smith")
course.print_details()
				
			

a) Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
– John Walker
– Jade Smith
Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
– John Walker
b) Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
– John Walker
– Jade Smith
Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
– John Walker
– Jade Smith
c) Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
– Jade Smith
Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
– John Walker
– Jade Smith
d) Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
– John Walker
– Jade Smith
Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:

Correct answer is: a) Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
– John Walker
– Jade Smith
Course Name: Python
Teacher: Mr. Dipesh Yadav
Students:
– John Walker
Explanation: The code defines a class `Course` with methods to add and remove students, and print the details of the course. The function generates a Python-themed object of the “Course” class with the teacher “Mr. Dipesh Yadav” as its name. Two students, “John Walker” and “Jade Smith”, are added to the course using the `add_student` method. The `print_details` method is called, which prints the course name, teacher, and the list of students. After that, the `remove_student` method is called to remove “Jade Smith” from the course. Finally, the `print_details` method is called again to print the updated course details. The correct output is option b) as it shows the initial course details with both students and the updated course details after removing “Jade Smith” from the list of students.

11). What is the output of the following code?

				
					class Shape:
    def calculate_area(self):
        pass

class Square(Shape):
    def __init__(self, side_length):
        self.side_length = side_length
    
    def calculate_area(self):
        return self.side_length ** 2

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height
    
    def calculate_area(self):
        return 0.5 * self.base * self.height

# Create objects of the Square and Triangle classes
square = Square(5)
triangle = Triangle(4, 6)
print("Square Area:", square.calculate_area())
print("Triangle Area:", triangle.calculate_area())
				
			

a) Square Area: 25, Triangle Area: 12
b) Square Area: 20, Triangle Area: 24
c) Square Area: 25, Triangle Area: 24
d) Square Area: 20, Triangle Area: 12

Correct answer is: a) Square Area: 25, Triangle Area: 12
Explanation: The code defines three classes: `Shape`, `Square`, and `Triangle`. The `Shape` class is the base class with a method `calculate_area()` that is not implemented. The `Square` class is a subclass of `Shape` and overrides the `calculate_area()` method to calculate the area of a square using the formula `side_length ** 2`. The `Triangle` class is also a subclass of `Shape` and overrides the `calculate_area()` method to calculate the area of a triangle using the formula `0.5 * base * height`. In the code, an object `square` of the `Square` class is created with a side length of 5, and an object `triangle` of the `Triangle` class is created with a base of 4 and a height of 6.

12). What is the output of the following code?

				
					class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    
    def print_details(self):
        print("Name:", self.name)
        print("Salary:", self.salary)

# Create an object of the Employee class
employee = Employee("John Walker", 50000)
employee.print_details()
				
			

a) Name: John Walker Salary: 50000
b) Name: None Salary: None
c) Name: John Walker Salary: None
d) Name: None Salary: 50000

Correct answer is: a) Name: John Walker Salary: 50000
Explanation: In the given code, an `Employee` class is defined with an `__init__` method and a `print_details` method. The `__init__` method initializes the `name` and `salary` attributes of the class. The `print_details` method prints the values of `name` and `salary` using the `print` function. After defining the class, an object of the `Employee` class is created with the name “John Walker” and a salary of 50000. The `print_details` method is then called on the `employee` object, which prints the name and salary as “John Walker” and 50000, respectively.

13). What is the output of the following code?

				
					class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    
    def print_details(self):
        print("Name:", self.name)
        print("Salary:", self.salary)

class Manager(Employee):
    def __init__(self, name, salary, department, bonus):
        super().__init__(name, salary)
        self.department = department
        self.bonus = bonus
    
    def calculate_total_compensation(self):
        total_compensation = self.salary + self.bonus
        return total_compensation

# Create an object of the Manager class
manager = Manager("John Walker", 60000, "Sales", 5000)
total_compensation = manager.calculate_total_compensation()
print("Total Compensation:", total_compensation)
				
			

a) Total Compensation: 65000
b) Total Compensation: 110000
c) Total Compensation: 60000
d) Total Compensation: 5000

Correct answer is: a) Total Compensation: 65000
Explanation: The code defines two classes: `Employee` and `Manager`. The `Manager` class is a subclass of the `Employee` class and inherits its attributes and methods. In the `Manager` class, the `__init__` method is overridden to include additional attributes `department` and `bonus`. In the code, an object `manager` of the `Manager` class is created with the following arguments: (“John Walker”, 60000, “Sales”, 5000). The `calculate_total_compensation` method is called on the `manager` object, which calculates the total compensation by adding the salary and bonus. The calculated `total_compensation` is then printed. Since the salary is 60000 and the bonus is 5000, the total compensation is 65000.

14). What is the output of the following code?

				
					class Customer:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
    
    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
        else:
            print("Insufficient balance")

# Create an object of the Customer class
customer = Customer("Jason Roy", 1000)
customer.deposit(500)
customer.withdraw(200)
print("Balance:", customer.balance)
				
			

a) “Insufficient balance”
b) 800
c) 1300
d) 1200

Correct answer is: c) 1300
Explanation: The code creates an object of the `Customer` class with the name “Jason Roy” and an initial balance of 1000. The `deposit()` method is then called, adding 500 to the balance. Next, the `withdraw()` method is called with an amount of 200. Since the amount is less than or equal to the balance, 200 is subtracted from the balance. Finally, the current balance of the customer object is printed, resulting in an output of “Balance: 1300”.

15). What is the output of the following code?

				
					class Customer:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
    
    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
        else:
            print("Insufficient balance")

class VIPCustomer(Customer):
    def __init__(self, name, balance, credit_limit, discount_rate):
        super().__init__(name, balance)
        self.credit_limit = credit_limit
        self.discount_rate = discount_rate
    
    def calculate_available_credit(self):
        available_credit = self.credit_limit - self.balance
        return available_credit

# Create an object of the VIPCustomer class
vip_customer = VIPCustomer("John Doe", 5000, 10000, 0.1)
available_credit = vip_customer.calculate_available_credit()
print("Available Credit:", available_credit)
				
			

a) Available Credit: 5000
b) Available Credit: 6000
c) Available Credit: 9000
d) Available Credit: 10000

Correct answer is: a) Available Credit: 5000
Explanation: The code defines two classes, `Customer` and `VIPCustomer`, where `VIPCustomer` is a subclass of `Customer`. The `VIPCustomer` class inherits the `__init__` method from the `Customer` class using the `super()` function. An object `vip_customer` is created using the `VIPCustomer` class, with the name “John Doe”, an initial balance of 5000, a credit limit of 10000, and a discount rate of 0.1. The `calculate_available_credit` method is called on the `vip_customer` object, which calculates the available credit by subtracting the balance from the credit limit. In this case, the available credit is 5000.

16). What is the output of the following code?

				
					class Phone:
    def __init__(self, brand, model, storage):
        self.brand = brand
        self.model = model
        self.storage = storage
    
    def make_call(self, number):
        print(f"Making a call to {number}")
    
    def send_text_message(self, number, message):
        print(f"Sending a text message to {number}: {message}")
    
    def check_storage_capacity(self):
        print(f"Storage capacity: {self.storage}GB")

# Create an object of the Phone class
phone = Phone("Apple", "iPhone 14", 256)
phone.make_call("1234567890")
phone.send_text_message("1234567890", "Hello!")
phone.check_storage_capacity()
				
			

a) Making a call to 1234567890
Sending a text message to 1234567890: Hello!
Storage capacity: 256GB
b) Making a call to 1234567890
Sending a text message to 1234567890: Hello!
c) Sending a text message to 1234567890: Hello!
Storage capacity: 256GB
d) Making a call to 1234567890

Correct answer is: a) Making a call to 1234567890
Sending a text message to 1234567890: Hello!
Storage capacity: 256GB
Explanation: The code creates an object of the `Phone` class with the brand “Apple”, model “iPhone 14”, and storage capacity of 256GB. The `make_call` method is then called with the number “1234567890”, which prints the message “Making a call to 1234567890”. Next, the `send_text_message` method is called with the number “1234567890” and the message “Hello!”, which prints the message “Sending a text message to 1234567890: Hello!”. Finally, the `check_storage_capacity` method is called, which prints the message “Storage capacity: 256GB”. Therefore, the correct output is option a) Making a call to 1234567890, Sending a text message to 1234567890: Hello!, Storage capacity: 256GB.

17). What is the output of the following code?

				
					class Laptop:
    def __init__(self, brand, model, storage):
        self.brand = brand
        self.model = model
        self.storage = storage
    
    def start_up(self):
        print("Starting up the laptop")
        print("Model: ", self.model)
    
    def shut_down(self):
        print("Shutting down the laptop")
    
    def check_storage_capacity(self):
        print(f"Storage capacity: {self.storage}GB")

# Create an object of the Laptop class
laptop = Laptop("Dell", "XPS 13", 1000)
laptop.start_up()
laptop.shut_down()
laptop.check_storage_capacity()
				
			

a) Starting up the laptop
Model: XPS 13
Shutting down the laptop
Storage capacity: 1000GB
b) Starting up the laptop
Model: Dell
Shutting down the laptop
Storage capacity: XPS 13GB
c) Starting up the laptop
Model: XPS 13
Shutting down the laptop
Storage capacity: XPS 13GB
d) Starting up the laptop
Model: Dell
Shutting down the laptop
Storage capacity: 1000GB

Correct answer is: a) Starting up the laptop
Model: XPS 13
Shutting down the laptop
Storage capacity: 1000GB
Explanation: The code creates an object of the `Laptop` class with the brand “Dell”, model “XPS 13”, and storage capacity of 1000GB. When `laptop.start_up()` is called, it prints “Starting up the laptop” and then “Model: XPS 13” because `self.model` refers to the model attribute of the `laptop` object, which is “XPS 13”. After that, `laptop.shut_down()` is called, which prints “Shutting down the laptop”. Finally, `laptop.check_storage_capacity()` is called, which prints “Storage capacity: 1000GB” because `self.storage` refers to the storage attribute of the `laptop` object, which is 1000.

18). What is the output of the following code?

				
					class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages
    
    def get_title(self):
        return self.title
    
    def get_author(self):
        return self.author
    
    def get_pages(self):
        return self.pages

# Create an object of the Book class
book = Book("Harry Potter", "J.K. Rowling", 300)
print("Title:", book.get_title())
print("Author:", book.get_author())
print("Pages:", book.get_pages())
				
			

a) Title: Harry Potter
Author: J.K. Rowling
Pages: 300
b) Harry Potter
J.K. Rowling
300
c) Title: “Harry Potter”
Author: “J.K. Rowling”
Pages: 300
d) “Harry Potter”
“J.K. Rowling”
300

Correct answer is: a) Title: Harry Potter
Author: J.K. Rowling
Pages: 300
Explanation: The code defines a class named `Book` with an initializer method (`__init__`) and three getter methods (`get_title`, `get_author`, `get_pages`). It then creates an instance of the `Book` class with the title “Harry Potter,” author “J.K. Rowling,” and 300 pages. The `print` statements display the output using the getter methods to retrieve the values from the `book` object. T

19). What is the output of the following code?

				
					class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages
    
    def get_title(self):
        return self.title
    
    def get_author(self):
        return self.author
    
    def get_pages(self):
        return self.pages
    
class EBook(Book):
    def __init__(self, title, author, pages, file_size, format):
        super().__init__(title, author, pages)
        self.file_size = file_size
        self.format = format
    
    def open_book(self):
        print("Opening the e-book")
    
    def close_book(self):
        print("Closing the e-book")

# Create an object of the EBook class
ebook = EBook("Harry Potter", "J.K. Rowling", 300, "10MB", "PDF")
print("Title:", ebook.get_title())
print("Author:", ebook.get_author())
print("Pages:", ebook.get_pages())
print("File Size:", ebook.file_size)
print("Format:", ebook.format)
ebook.open_book()
ebook.close_book()
				
			

a) Title: Harry Potter
Author: J.K. Rowling
Pages: 300
File Size: 10MB
Format: PDF
Opening the e-book
Closing the e-book
b) Title: Harry Potter
Author: J.K. Rowling
Pages: 300
File Size: 10MB
Format: PDF
c) Opening the e-book
Closing the e-book
d) An error will occur due to incorrect method calls.

Correct answer is: a) Title: Harry Potter
Author: J.K. Rowling
Pages: 300
File Size: 10MB
Format: PDF
Opening the e-book
Closing the e-book
Explanation: The code defines two classes, `Book` and `EBook`, where `EBook` is a subclass of `Book`. The `EBook` class inherits the `__init__` method from the `Book` class using the `super()` function. It also has additional methods `open_book()` and `close_book()`. In the code, an object `ebook` is created with the title “Harry Potter”, author “J.K. Rowling”, 300 pages, a file size of “10MB”, and format “PDF”. The `print` statements then retrieve and display the title, author, pages, file size, and format of the `ebook` object. Finally, the `open_book()` and `close_book()` methods are called.

20). What is the output of the following code?

				
					class ShoppingCart:
    def __init__(self):
        self.items = []
        self.total_cost = 0
    
    def add_item(self, item, cost):
        self.items.append(item)
        self.total_cost += cost
    
    def remove_item(self, item, cost):
        if item in self.items:
            self.items.remove(item)
            self.total_cost -= cost
    
    def calculate_total_cost(self):
        return self.total_cost

# Create an object of the ShoppingCart class
cart = ShoppingCart()
cart.add_item("Shirt", 250)
cart.add_item("Pants", 500)
cart.add_item("Shoes", 1000)
cart.remove_item("Shirt", 250)
total_cost = cart.calculate_total_cost()
print("Items in cart:", cart.items)
print("Total Cost:", total_cost)
				
			

a) Items in cart: [‘Shirt’, ‘Pants’, ‘Shoes’], Total Cost: 1450
b) Items in cart: [‘Pants’, ‘Shoes’], Total Cost: 1250
c) Items in cart: [‘Pants’, ‘Shoes’], Total Cost: 1500
d) Items in cart: [‘Shirt’, ‘Pants’, ‘Shoes’], Total Cost: 1000

Correct answer is: b) Items in cart: [‘Pants’, ‘Shoes’], Total Cost: 1500
Explanation: The `ShoppingCart` class is defined with an `__init__` method to initialize the `items` list and `total_cost` to 0. The `add_item` method adds an item to the `items` list and increases the `total_cost` by the specified cost. The `remove_item` method removes an item from the `items` list and decreases the `total_cost` by the specified cost. The `calculate_total_cost` method returns the total cost.

21). What is the output of the following code?

				
					class Animal:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    
    def print_details(self):
        print("Name:", self.name)
        print("Color:", self.color)

# Create an object of the Animal class
animal = Animal("Lion", "Golden")
animal.print_details()
				
			

a) Name: Lion
Color: Golden
b) Name: Tiger
Color: Yellow
c) Name: Elephant
Color: Gray
d) Name: Giraffe
Color: Brown

Correct answer is: a) Name: Lion, Color: Golden
Explanation: The code defines a class `Animal` with an `__init__` method and a `print_details` method. The `__init__` method initializes the attributes `name` and `color` of the object, while the `print_details` method prints the values of these attributes. In the code, an object `animal` of the `Animal` class is created with the name “Lion” and the color “Golden”. The `print_details` method is then called on the `animal` object.

22). What is the output of the following code?

				
					class Animal:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    
    def print_details(self):
        print("Name:", self.name)
        print("Color:", self.color)
        
class Dog(Animal):
    def __init__(self, name, color, breed, weight):
        super().__init__(name, color)
        self.breed = breed
        self.weight = weight
    
    def print_details(self):
        super().print_details()
        print("Breed:", self.breed)
        print("Weight:", self.weight)

# Create an object of the Dog class
dog = Dog("Marco", "Golden", "Golden Retriever", 50)
dog.print_details()
				
			

a) Name: Marco, Color: Golden, Breed: Golden Retriever, Weight: 50
b) Name: Golden, Color: Marco, Breed: Golden Retriever, Weight: 50
c) Name: Marco, Color: Golden, Breed: Golden Retriever, Weight: 50, Color: Marco
d) Name: Golden, Color: Marco, Breed: Golden Retriever, Weight: 50, Color: Golden

Correct answer is: a) Name: Marco, Color: Golden, Breed: Golden Retriever, Weight: 50
Explanation: The code defines two classes, `Animal` and `Dog`. The `Dog` class is a subclass of `Animal` and inherits its `__init__` and `print_details` methods. The `Dog` class also has its own `__init__` method, which takes additional parameters for `breed` and `weight`. In the code, an object `dog` of the `Dog` class is created with the arguments “Marco”, “Golden”, “Golden Retriever”, and 50. When the `print_details` method is called on this `dog` object, it first calls the `print_details` method of the superclass `Animal` using `super().print_details()`. This prints the name and color inherited from the `Animal` class. After that, it prints the additional attributes specific to the `Dog` class, which are the breed and weight.

Python OOPS MCQ : Set 3

Python OOPS MCQ

1). What is the output of the following code?

				
					class MyClass:
    def __init__(self, name):
        self.name = name
    
    def display_name(self):
        print("Name:", self.name)

# Create an object of the class
obj = MyClass("Omkar")
obj.display_name()
				
			

Correct answer is: a) Name: Omkar
Explanation: The code defines a class called `MyClass` with an initializer method (`__init__`) and a `display_name` method. The `__init__` method initializes the instance variable `name` with the value passed as an argument. The value of ‘name’ is printed by the ‘display_name’ method. In the given code, an object `obj` of `MyClass` is created with the name “Omkar”. Then, the `display_name` method is called on `obj`, which prints “Name: Omkar”. Therefore, the output of the code is “Name: Omkar”.

2). What is the output of the following code?

				
					class MyClass:
    def __init__(self):
        self.instance_var = 25

# Create an object of the class
obj = MyClass()
print(obj.instance_var)
				
			

a) 25
b) None
c) AttributeError: ‘MyClass’ object has no attribute ‘instance_var’
d) SyntaxError: invalid syntax

Correct answer is: a) 25
Explanation: The code defines a class named `MyClass` with a constructor method `__init__`. Inside the constructor, an instance variable `instance_var` is assigned the value 25. After that, an object `obj` of the `MyClass` class is created using the constructor. When `obj.instance_var` is printed, it will output the value of the `instance_var` variable, which is 25. Therefore, the output of the code is 25.

3). What is the output of the following code?

				
					class MyClass:
    def __init__(self, name):
        self.name = name
    
    def display_name(self):
        print("Name:", self.name)
    
    def update_name(self, new_name):
        self.name = new_name

# Create an object of the class
obj = MyClass("Omkar")
obj.display_name()

obj.update_name("Ketan")
obj.display_name()
				
			

a) Name: Omkar
Name: Ketan
b) Name: Ketan
Name: Omkar
c) Name: Omkar
Name: Omkar
d) Name: Ketan
Name: Ketan

Correct answer is: a) Name: Omkar, Name: Ketan
Explanation: The code defines a class `MyClass` with an `__init__` method to initialize the `name` attribute, a `display_name` method to print the name, and an `update_name` method to update the name attribute. The object `obj` is created with the name “Omkar” and the `display_name` method is called, which prints “Name: Omkar”. Then, the `update_name` method is called to update the name attribute to “Ketan”. Finally, the `display_name` method is called again, which prints “Name: Ketan”.

4). What is the output of the following code?

				
					class MyClass:
    class_var = "Hello"
print(MyClass.class_var)
				
			

a) “Hello”
b) MyClass.class_var
c) AttributeError: type object ‘MyClass’ has no attribute ‘class_var’
d) SyntaxError: invalid syntax

Correct answer is: a) “Hello”
Explanation: In the given code, a class `MyClass` is defined with a class variable `class_var` assigned the value “Hello”. When the line `print(MyClass.class_var)` is executed, it accesses the class variable `class_var` using the class name `MyClass`. Therefore, the output of the code is “Hello”. The `print()` function displays the value of the class variable, which is “Hello” in this case.

5). What is the output of the following code?

				
					class MyClass:
    @staticmethod
    def static_method():
        print("This is a static method")

MyClass.static_method()
				
			

b) This is an instance method
c) AttributeError: ‘MyClass’ object has no attribute ‘static_method’
d) SyntaxError: invalid syntax

Correct answer is: a) This is a static method
Explanation: The output of the given code will be “This is a static method”. The code defines a class called `MyClass` with a static method named `static_method`. When the method is called using `MyClass.static_method()`, it prints the string “This is a static method” to the console. Static methods can be called on the class itself without creating an instance of the class, and they are not bound to any specific instance.

6). What is the output of the following code?

				
					class MyClass:
    class_var = "Hello"
    
    @classmethod
    def class_method(cls):
        print("Class variable:", cls.class_var)

MyClass.class_method()
				
			

a) Class variable: Hello
b) Class variable: MyClass.class_var
c) Class variable: Class method
d) Error: class_method() cannot be called directly

Correct answer is: a) Class variable: Hello
Explanation: “Class variable: Hello” will be the output of the given code. In the code, the class `MyClass` has a class variable `class_var` initialized with the string “Hello”. The `class_method` is a class method decorated with `@classmethod`. When the `class_method()` is called on the class `MyClass` using `MyClass.class_method()`, it will print the value of the class variable `class_var`, which is “Hello”. Therefore, the output will be “Class variable: Hello”.

7). What is the output of the following code?

				
					class MyClass:
    pass

obj = MyClass()
print("Class name:", obj.__class__.__name__)
print("Module name:", obj.__module__)
				
			

a) Class name: MyClass, Module name: __main__
b) Class name: MyClass, Module name: MyClass
c) Class name: object, Module name: __main__
d) Class name: object, Module name: MyClass

Correct answer is: a) Class name: MyClass, Module name: __main__
Explanation: In the given code, an instance of the class `MyClass` is created using the statement `obj = MyClass()`. The `__class__.__name__` attribute is used to retrieve the class name of the object, which in this case is “MyClass”. The `__module__` attribute is used to retrieve the name of the module in which the class is defined. When running the code directly, without importing the class from another module, the module name is set to “__main__”.

8). What is the output of the following code?

				
					    def __init__(self, name):
        self.name = name
    
    def display_name(self):
        print("Name:", self.name)

if __name__ == '__main__':
    obj = MyClass("Jason")
    obj.display_name()
				
			

a) Name: Jason
b) Name: MyClass
c) MyClass(“Jason”)
d) Name:

Correct answer is: a) Name: Jason
Explanation: The code defines a class `MyClass` with an `__init__` method that takes a parameter `name` and assigns it to the instance variable `self.name`. It also has a method `display_name` that prints the value of `self.name` preceded by the string “Name:”. In the `if __name__ == ‘__main__’:` block, an instance `obj` of `MyClass` is created with the argument “Jason”. Then, the `display_name` method of `obj` is called, which prints “Name: Jason”. Hence, the output of the code will be “Name: Jason”.

9). What is the output of the following code?

				
					class ParentClass:
    def parent_method(self):
        print("Parent method")

class ChildClass(ParentClass):
    def child_method(self):
        print("Child method")

# Create an object of the child class
obj = ChildClass()
obj.parent_method()
obj.child_method()

				
			

a) Parent method
Child method
b) Child method
Parent method
c) Error: ChildClass does not have a parent_method()
d) Error: ChildClass does not have a child_method()

Correct answer is: a) Parent method
Child method
Explanation: The code defines two classes: `ParentClass` and `ChildClass`. The `ChildClass` inherits from `ParentClass`. We create an object `obj` of the `ChildClass`. When we call `obj.parent_method()`, it invokes the `parent_method()` defined in the `ParentClass`, which prints “Parent method”. Similarly, when we call `obj.child_method()`, it invokes the `child_method()` defined in the `ChildClass`, which prints “Child method”.

10). What is the output of the following code?

				
					class ParentClass1:
    def parent_method1(self):
        print("Parent method 1")

class ParentClass2:
    def parent_method2(self):
        print("Parent method 2")

class ChildClass(ParentClass1, ParentClass2):
    def child_method(self):
        print("Child method")

# Create an object of the child class
obj = ChildClass()
obj.parent_method1()
obj.parent_method2()
obj.child_method()
				
			

a) Parent method 1
Parent method 2
Child method
b) Parent method 2
Parent method 1
Child method
c) Parent method 1
Child method
Parent method 2
d) Parent method 2
Child method
Parent method 1

Correct answer is: a) Parent method 1, Parent method 2, Child method
Explanation: The `ChildClass` inherits from `ParentClass1` and `ParentClass2`. When an object of `ChildClass` is created and its methods are called, the output will be “Parent method 1”, “Parent method 2”, and “Child method” in that order. This is because the inherited methods can be accessed and called using the object of the child class.

11). What is the output of the following code?

				
					class GrandparentClass:
    def grandparent_method(self):
        print("Grandparent method")

class ParentClass(GrandparentClass):
    def parent_method(self):
        print("Parent method")

class ChildClass(ParentClass):
    def child_method(self):
        print("Child method")

# Create an object of the child class
obj = ChildClass()
obj.grandparent_method()
obj.parent_method()
obj.child_method()
				
			

a) Grandparent method, Parent method, Child method
b) Child method, Parent method, Grandparent method
c) Grandparent method
d) Parent method, Child method

Correct answer is: a) Grandparent method, Parent method, Child method
Explanation: The given code defines three classes: `GrandparentClass`, `ParentClass`, and `ChildClass`. The `ChildClass` inherits from `ParentClass`, which in turn inherits from `GrandparentClass`.

12). What is the output of the following code?

				
					class ParentClass:
    def parent_method(self):
        print("Parent method")

class ChildClass1(ParentClass):
    def child_method1(self):
        print("Child 1 method")

class ChildClass2(ParentClass):
    def child_method2(self):
        print("Child 2 method")

# Create objects of the child classes
obj1 = ChildClass1()
obj2 = ChildClass2()

obj1.parent_method()
obj1.child_method1()

obj2.parent_method()
obj2.child_method2()
				
			

a) Parent method, Child 1 method, Parent method, Child 2 method
b) Child 1 method, Parent method, Child 2 method, Parent method
c) Parent method, Child 1 method, Child 2 method, Parent method
d) Child 1 method, Parent method, Parent method, Child 2 method

Correct answer is: c) Parent method, Child 1 method, Child 2 method, Parent method
Explanation: The code defines three classes: `ParentClass`, `ChildClass1`, and `ChildClass2`. `ChildClass1` and `ChildClass2` inherit from `ParentClass`. Two objects, `obj1` and `obj2`, are created using the child classes.
– The following methods are called:
1. `obj1.parent_method()`: This calls the `parent_method()` of the `ParentClass`, which prints “Parent method”.
2. `obj1.child_method1()`: This calls the `child_method1()` of `ChildClass1`, which prints “Child 1 method”.
3. `obj2.parent_method()`: This calls the `parent_method()` of the `ParentClass`, which prints “Parent method”.
4. `obj2.child_method2()`: This calls the `child_method2()` of `ChildClass2`, which prints “Child 2 method”.

13). What is the output of the following code?

				
					class ParentClass:
    def parent_method(self):
        print("Parent method")

class ChildClass(ParentClass):
    def parent_method(self):
        print("Child method (overrides parent)")

# Create an object of the child class
obj = ChildClass()
obj.parent_method()
				
			

a) “Parent method”
b) “Child method (overrides parent)”
c) Error: The code will raise an exception
d) No output: The code will not execute

Correct answer is: b) “Child method (overrides parent)”
Explanation: The code defines two classes, `ParentClass` and `ChildClass`, where `ChildClass` is a subclass of `ParentClass`. The `ChildClass` overrides the `parent_method` of the parent class. When an object of the `ChildClass` is created and the `parent_method()` is called on that object, the output will be “Child method (overrides parent)”. This is because the method in the child class overrides the method in the parent class, and the overridden method is executed when called on an instance of the child class.

14). What is the output of the following code?

				
					class MyClass:
    def method(self, param1, param2=None):
        if param2 is None:
            print("Single parameter:", param1)
        else:
            print("Two parameters:", param1, param2)

# Create an object of the class
obj = MyClass()

# Call the method with different number of arguments
obj.method("Hello")
obj.method("Hello", "World")
				
			

a) Single parameter: Hello, Two parameters: Hello World
b) Single parameter: Hello
Two parameters: Hello World
c) Two parameters: Hello
Two parameters: Hello World
d) Two parameters: Hello World

Correct answer is: b) Single parameter: Hello
Two parameters: Hello World
Explanation: The code defines a class `MyClass` with a method `method` that takes two parameters, `param1` and `param2`. The `param2` parameter is optional and has a default value of `None`. In the main part of the code, an object `obj` of the class `MyClass` is created. The method `method` is then called twice with different arguments. When `obj.method(“Hello”)` is called, it matches the method signature with a single argument. Inside the method, the condition `param2 is None` is true because no value is provided for `param2`. Therefore, the output is “Single parameter: Hello”. When `obj.method(“Hello”, “World”)` is called, it matches the method signature with two arguments. Inside the method, the condition `param2 is None` is false because a value is provided for `param2`. Therefore, the output is “Two parameters: Hello World”.

15). What is the output of the following code?

				
					from abc import ABC, abstractmethod
class AbstractClass(ABC):
    @abstractmethod
    def abstract_method(self):
        pass

class ConcreteClass(AbstractClass):
    def abstract_method(self):
        print("Implemented abstract method")

# Create an object of the concrete class
obj = ConcreteClass()
obj.abstract_method()
				
			

a) “Implemented abstract method”
b) This code will produce an error.
c) “AbstractClass object has no attribute ‘abstract_method'”
d) “ConcreteClass object has no attribute ‘abstract_method'”

Correct answer is: a) “Implemented abstract method”
Explanation: In the given code, we define an abstract base class `AbstractClass` that inherits from the `ABC` class. The `AbstractClass` contains an abstract method `abstract_method` decorated with the `@abstractmethod` decorator. The `ConcreteClass` inherits from `AbstractClass` and implements the `abstract_method` by printing “Implemented abstract method”.

16). What is the output of the following code?

				
					    def __init__(self):
        self.__private_var = 25
    
    def __private_method(self):
        print("Private method")

    def public_method(self):
        print("Public method")
        self.__private_method()

# Create an object of the class
obj = MyClass()

# Access public method and variable
obj.public_method()
print(obj._MyClass__private_var)
				
			

a) “Public method” followed by an error
b) “Public method” followed by “Private method” and then 25
c) “Private method” followed by an error
d) “Private method” followed by “Public method” and then 25

Correct answer is: b) “Public method” followed by “Private method” and then 25
Explanation: The code defines a class `MyClass` with a private variable `__private_var` and a private method `__private_method`. The `public_method` is a public method that prints “Public method” and calls the private method `__private_method()`. When an object `obj` of the class is created, and the `public_method()` is called, it will print “Public method” and then call the private method `__private_method()`, which will print “Private method”. Finally, the statement `print(obj._MyClass__private_var)` accesses the private variable `__private_var` using name mangling syntax and prints its value, which is 25.

17). What is the output of the following code?

				
					class Employee:
    def __init__(self, emp_id, name, salary):
        self.emp_id = emp_id
        self.name = name
        self.salary = salary
    
    def display_details(self):
        print("Employee ID:", self.emp_id)
        print("Name:", self.name)
        print("Salary:", self.salary)

class EmployeeManagementApp:
    def __init__(self):
        self.employees = []
    
    def add_employee(self, employee):
        self.employees.append(employee)
    
    def remove_employee(self, employee):
        if employee in self.employees:
            self.employees.remove(employee)
    
    def display_all_employees(self):
        for employee in self.employees:
            employee.display_details()

# Create an instance of the EmployeeManagementApp class
app = EmployeeManagementApp()

# Add employees to the application
employee1 = Employee(1, "Robert Yates", 50000)
employee2 = Employee(2, "Kelly Smith", 60000)
employee3 = Employee(3, "Michael Potter", 55000)

app.add_employee(employee1)
app.add_employee(employee2)
app.add_employee(employee3)

# Display all employees in the application
app.display_all_employees()
				
			

a) Employee ID: 3, Name: Robert Yates, Salary: 50000
Employee ID: 2, Name: Kelly Smith, Salary: 60000
Employee ID: 1, Name: Michael Potter, Salary: 55000
b) Employee ID: 1, Name: Robert Yates, Salary: 50000,
Employee ID: 2, Name: Kelly Smith, Salary: 60000,
Employee ID: 3, Name: Michael Potter, Salary: 55000,
c) Employee ID: 1, Name: Robert Yates, Salary: 50000
Employee ID: 3, Name: Kelly Smith, Salary: 60000
Employee ID: 2, Name: Michael Potter, Salary: 55000,
d) This code will result in an error.

Correct answer is: b) Employee ID: 1, Name: Robert Yates, Salary: 50000,
Employee ID: 2, Name: Kelly Smith, Salary: 60000,
Employee ID: 3, Name: Michael Potter, Salary: 55000,
Explanation: The code defines two classes, `Employee` and `EmployeeManagementApp`. The `Employee` class has an `__init__` method to initialize employee attributes and a `display_details` method to print the employee details. The `EmployeeManagementApp` class is responsible for managing a list of employees. In the code, an instance of the `EmployeeManagementApp` class is created, and three instances of the `Employee` class are created with different employee details. These employee instances are added to the `EmployeeManagementApp` instance using the `add_employee` method. Finally, the `display_all_employees` method is called on the `EmployeeManagementApp` instance, which iterates through the list of employees and calls the `display_details` method for each employee. This results in printing the details of all employees.

18). What is the output of the following code?

				
					class MyClass:
    def __init__(self):
        self._my_property = None
    
    @property
    def my_property(self):
        return self._my_property
    
    @my_property.setter
    def my_property(self, value):
        self._my_property = value

# Create an object of the class
obj = MyClass()

# Access the property
obj.my_property = "Hello"
print(obj.my_property)
				
			

a) “Hello”
b) None
c) Error: AttributeError
d) Error: SyntaxError

Correct answer is: a) “Hello”
Explanation: The code defines a class `MyClass` with a private instance variable `_my_property` and a property `my_property` that allows getting and setting the value of `_my_property`. After creating an object `obj` of the class `MyClass`, the line `obj.my_property = “Hello”` sets the value of `my_property` to “Hello” using the property setter. Finally, when `print(obj.my_property)` is executed, it accesses the value of `my_property`, which is “Hello” at that point, and prints it as the output.

19). What is the output of the following code?

				
					import math
class Circle:
    def __init__(self, radius):
        self.radius = radius
    
    def calculate_area(self):
        return math.pi * self.radius**2

# Create an object of the class
circle = Circle(10)
area = circle.calculate_area()
print("Area of the circle:", area)
				
			

a) Area of the circle: 31.41592653589793
b) Area of the circle: 314.1592653589793
c) Area of the circle: 3141.592653589793
d) Area of the circle: 0.3141592653589793

Correct answer is:
b) Area of the circle: 314.1592653589793
Explanation: The given code defines a class `Circle` with an `__init__` method and a `calculate_area` method. The `__init__` method initializes the `radius` attribute, and the `calculate_area` method calculates the area of the circle using the formula `math.pi * self.radius**2`. In the code, an object `circle` is created with a radius of 10. The `calculate_area` method is then called on the `circle` object, and the result is stored in the `area` variable. Finally, the calculated area is printed using the `print` statement.

20). What is the output of the following code?

				
					class Class1:
    def method1(self):
        print("Method 1 of Class 1")

class Class2(Class1):
    def method2(self):
        print("Method 2 of Class 2")

class Class3(Class2):
    def method3(self):
        print("Method 3 of Class 3")

class Class4(Class3):
    def method4(self):
        print("Method 4 of Class 4")

class Class5(Class4):
    def method5(self):
        print("Method 5 of Class 5")

# Create an object of the final class and access methods
obj = Class5()
obj.method1()
obj.method2()
obj.method3()
obj.method4()
obj.method5()
				
			

a) Method 1 of Class 1
Method 2 of Class 2
Method 3 of Class 3
Method 4 of Class 4
Method 5 of Class 5
b) Method 1 of Class 1
c) Method 1 of Class 1
Method 2 of Class 2
d) Method 1 of Class 1
Method 2 of Class 2
Method 3 of Class 3

Correct answer is: a) Method 1 of Class 1
Method 2 of Class 2
Method 3 of Class 3
Method 4 of Class 4
Method 5 of Class 5
Explanation: The given code defines a hierarchy of classes: Class1, Class2, Class3, Class4, and Class5. Each class has a method specific to its class name. The code creates an object of Class5 and calls various methods on it. Since Class5 is the final class in the inheritance hierarchy, it inherits all the methods from its superclass, Class4, which in turn inherits methods from Class3, Class2, and Class1.

21). What is the output of the following code?

				
					class MyClass:
    def __init__(self):
        pass
# Create an object of the class
obj = MyClass()

# Set instance variable dynamically
setattr(obj, "variable", "Value")

# Get instance variable dynamically
value = getattr(obj, "variable")
print(value)
				
			

a) “Value”
b) None
c) AttributeError: ‘MyClass’ object has no attribute ‘variable’
d) SyntaxError: invalid syntax

Correct answer is: a) “Value”
Explanation: The code creates an instance of the `MyClass` class using `obj = MyClass()`. Then, the `setattr` function is used to dynamically set an instance variable named “variable” with the value “Value”. Next, the `getattr` function retrieves the value of the “variable” instance variable. Finally, the value is printed, which will be “Value”. This is because `setattr` sets the instance variable “variable” to “Value”, and `getattr` retrieves its value successfully. Therefore, the output of the code will be “Value”.

22). What is the output of the following code?

				
					class MyClass:
    def __init__(self):
        self.__private_var = 10
    
    def __private_method(self):
        print("Private method")

    def public_method(self):
        print("Public method")
        self.__private_method()

# Create an object of the class
obj = MyClass()

# Access public method and variable
obj.public_method()
				
			

a) “Public method”
b) “Private method”
c) “Public method” followed by “Private method”
d) This code will result in an error.

Correct answer is: c) “Public method” followed by “Private method”
Explanation: The code creates a class `MyClass` with a private variable `__private_var` and a private method `__private_method`. It also has a public method `public_method` that prints “Public method” and calls the private method `__private_method`. When an object `obj` of the class `MyClass` is created, and the `public_method` is invoked using `obj.public_method()`, it first prints “Public method”. Then, within the `public_method`, the private method `__private_method` is called using `self.__private_method()`, which results in printing “Private method”.

Python OOPS MCQ : Set 2

Python OOPS MCQ

1). What is the purpose of the `@classmethod` decorator in Python?

a) It allows a method to be called without creating an instance of the class.
b) It converts a class method into an instance method.
c) It enables inheritance between classes.
d) It defines a method within a class.

Correct answer is: a) It allows a method to be called without creating an instance of the class.
Explanation: The `@classmethod` decorator is used to define a class method in Python. There is no need to create an instance when using class methods on the class itself.

2). What is the difference between public, protected, and private access modifiers in Python?

a) Public attributes are accessible within the class, protected attributes are accessible within the class and its subclasses, and private attributes are accessible only within the class.
b) Public attributes are accessible only within the class, protected attributes are accessible within the class and its subclasses, and private attributes are accessible within the module.
c) Public attributes are accessible within the class and its subclasses, protected attributes are accessible within the module, and private attributes are accessible only within the class.
d) Public attributes are accessible within the class and its subclasses, protected attributes are accessible within the module, and private attributes are accessible within the class.

Correct answer is: a) Public attributes are accessible within the class, protected attributes are accessible within the class and its subclasses, and private attributes are accessible only within the class.
Explanation: In Python, attributes and methods can have different access modifiers. Public attributes are accessible within the class, protected attributes are accessible within the class and its subclasses, and private attributes are accessible only within the class.

3). What is the purpose of the `__slots__` attribute in Python classes?
a) It defines the class attributes.
b) It restricts the creation of instance attributes to a predefined set.
c) It specifies the superclass of a class.
d) It enables multiple inheritance.

Correct answer is: b) It restricts the creation of instance attributes to a predefined set.
Explanation: The `__slots__` attribute in Python classes restricts the creation of instance attributes to a specific set of names. It can optimize memory usage by avoiding the creation of a dynamic dictionary for every instance.

4). Which of the following is true about method resolution order (MRO) in Python?

a) MRO defines the order in which methods are inherited from multiple superclasses.
b) MRO determines the access level of methods and attributes.
c) MRO specifies the number of methods that can be defined in a class.
d) MRO determines the lifespan of an instance.

Correct answer is: a) MRO defines the order in which methods are inherited from multiple superclasses.
Explanation: Method resolution order (MRO) in Python defines the order in which methods are inherited from multiple superclasses. It is determined using the C3 linearization algorithm.

5). What is the purpose of the `__new__` method in Python?

a) It is used to define class attributes.
b) It is automatically called when an instance is about to be destroyed.
c) It is used to create and initialize a new instance of a class.
d) It is used to delete an instance of a class.

Correct answer is: c) It is used to create and initialize a new instance of a class.
Explanation: The `__new__` method in Python is responsible for creating and initializing a new instance of a class. It is called before the `__init__` method.

6). What is the difference between an instance attribute and a class attribute in Python?

a) Instance attributes are defined within methods, while class attributes are defined outside methods.
b) Instance attributes are accessible only within the class, while class attributes are accessible outside the class.
c) Instance attributes have a different value for each instance of a class, while class attributes have the same value for all instances.
d) Instance attributes are used to define methods, while class attributes are used to define attributes.

Correct answer is: c) Instance attributes have a different value for each instance of a class, while class attributes have the same value for all instances.
Explanation: Instance attributes have unique values for each instance of a class, while class attributes have the same value shared among all instances.

7). Which of the following is true about composition and aggregation in Python?

a) Composition is a stronger form of relationship than aggregation.
b) Aggregation is a stronger form of relationship than composition.
c) Composition implies a “has-a” relationship, while aggregation implies a “part-of” relationship.
d) Composition and aggregation are the same and can be used interchangeably.

Correct answer is: c) Composition implies a “has-a” relationship, while aggregation implies a “part-of” relationship.
Explanation: Composition and aggregation represent different forms of relationships in object-oriented programming. When two objects are composed of one another, there is a clear “has-a” link present. Aggregation implies a looser “part-of” relationship, where one object is associated with other objects.

8). What is the purpose of the `__getitem__` method in Python?

a) It is used to define class attributes.
b) It is used to access items from a class using index-based notation.
c) It is used to compare two instances of a class.
d) It is used to iterate over items in a class.

Correct answer is: b) It is used to access items from a class using index-based notation.
Explanation: The `__getitem__` method in Python is used to define the behavior of accessing items from a class using index-based notation (e.g., `my_object[index]`).

9). What is the purpose of the `__setitem__` method in Python?

a) It is used to define class attributes.
b) It is used to modify items in a class using index-based notation.
c) It is used to convert an instance to a string representation.
d) It is used to compare two instances of a class.

Correct answer is: b) It is used to modify items in a class using index-based notation.
Explanation: The `__setitem__` method in Python is used to define the behavior of modifying items in a class using index-based notation (e.g., `my_object[index] = value`).

10). What is the purpose of the `__len__` method in Python?

a) It is used to define class attributes.
b) It is used to compare two instances of a class.
c) It is used to convert an instance to a string representation.
d) It is used to determine the length of an object.

Correct answer is: d) It is used to determine the length of an object.
Explanation: The `__len__` method in Python is used to define the behavior of determining the length of an object. It is automatically called when the `len()` function is used on an instance of the class.

11). What is the purpose of the `__eq__` method in Python?

a) It is used to define class attributes.
b) It is used to initialize the attributes of a class.
c) It is used to compare two instances of a class for equality.
d) It is used to convert an instance to a string representation.

Correct answer is: c) It is used to compare two instances of a class for equality.
Explanation: The `__eq__` method in Python is used to define the behavior of comparing two instances of a class for equality using the `==` operator.

12). Which of the following is an advantage of using composition over inheritance in Python?

a) Composition provides a more flexible and loosely coupled design.
b) Inheritance allows for code reuse without modifying existing classes.
c) Composition leads to simpler and more concise code.
d) Inheritance provides better performance compared to composition.

Correct answer is: a) Composition provides a more flexible and loosely coupled design.
Explanation: Composition allows for more flexibility and loose coupling between classes, making it easier to change the behavior of a class without modifying its internal structure.

13). What is the purpose of the `__call__` method in Python?

a) It is used to define class attributes.
b) It is used to create a new instance of a class.
c) It is used to invoke an instance of a class as a function.
d) It is used to define a class decorator.

Correct answer is: c) It is used to invoke an instance of a class as a function.
Explanation: The `__call__` method in Python is used to define the behavior of invoking an instance of a class as a function, allowing instances to be called like a function.

14). What is the purpose of the `__iter__` method in Python?

a) It is used to define class attributes.
b) It is used to initialize the attributes of a class.
c) It is used to iterate over items in a class.
d) It is used to compare two instances of a class.

Correct answer is: c) It is used to iterate over items in a class.
Explanation: The `__iter__` method in Python is used to define the behavior of iterating over items in a class using a loop or other iteration constructs.

15). What is the most striking feature of class?

a) Data encapsulation
b) Data abstraction
c) Inheritance
d) Polymorphism

Correct answer is: a) Data encapsulation
Explanation: Data abstraction is the process of hiding the implementation details of an object from the user. This allows the user to focus on the object’s functionality, without having to worry about how it works. Inheritance is the process of one class inheriting the properties and methods of another class. This allows for code reuse and makes it easier to create complex objects. The capacity of an object to assume various forms is known as polymorphism. This is achieved through the use of virtual methods, which can be overridden by subclasses.

16). Why classes are known as abstract data types (ADT)?

a) Because they can be used to represent abstract concepts
b) Because they can be used to represent real-world objects
c) Because they can be used to represent both abstract concepts and real-world objects
d) None of the above

Correct answer is: c) Because they can be used to represent both abstract concepts and real-world objects**
Explanation: Abstract concepts are things that do not have a physical representation in the real world, such as the concept of “love” or the concept of “justice”. Real-world objects are things that have a physical representation in the real world, such as a car or a house. Classes can be used to represent both abstract concepts and real-world objects because they allow the programmer to define the data and the methods that are associated with the object. This allows the programmer to create objects that have the same properties and behavior, regardless of whether they represent an abstract concept or a real-world object.

17). Which of the following is not true about the object-oriented approach?

a) It supports both abstract data and class
b) It provides polymorphism and inheritance
c) It is a programming paradigm
d) It is a way of organizing code

Correct answer is: c) It is a programming paradigm
Explanation: A programming paradigm is a way of organizing code that is based on a particular set of concepts. For example, the procedural programming paradigm is based on the concept of procedures, while the object-oriented programming paradigm is based on the concept of objects. The object-oriented approach is a set of concepts that can be used to implement a programming paradigm. These concepts include classes, objects, methods, inheritance, and polymorphism.

18). Which language among the following support an object-oriented approach?

a) Python
b) C++
c) Java
d) All of the above

Correct answer is: d) All of the above
Explanation: Object-oriented programming is a programming paradigm that uses objects and classes to represent data and behavior. Class instances, or objects, each have a distinct state and behaviour. Classes are templates for creating objects, and they define the data and behavior that all objects of that class will have. Programming languages that focus on objects include Python, C++, and Java. This means that they support the concepts of objects, classes, inheritance, and polymorphism.

19). Which of the following is not a valid attribute of a class?

a) Data members
b) Methods
c) Functions
d) Constructors

Correct answer is: c) Functions
Explanation: Attributes are variables that are associated with a class. They can be used to store data that is common to all objects of that class. Methods are functions that are associated with a class. They can be used to perform operations on objects of that class.

20). Which of the following is not a valid method of a class?

a) init
b) str
c) del
d) main

Correct answer is: d) main
Explanation: The init method is the constructor method of a class. It is called when an object of that class is created. The str method is the string representation method of a class. It is called when an object of that class is converted to a string. The del method is the destructor method of a class. It is called when an object of that class is deleted.

21). What is encapsulation?

a) The ability of an object to take on different forms
b) The process of one class inheriting the properties and methods of another class
c) The process of hiding the implementation details of an object from the user
d) The process of binding together the data and the functions that operate on that data

Correct answer is: c) The process of hiding the implementation details of an object from the user
Explanation: Encapsulation is one of the most important features of object-oriented programming. It allows for the separation of the interface from the implementation. This makes it simpler to read and maintain the code.

22). What is the difference between an abstract class and an interface?

a) An abstract class is a class that can be instantiated, while an interface is a class that cannot be instantiated
b) An abstract class is a class that can be inherited, while an interface is a class that cannot be inherited
c) An interface can only contain abstract methods, whereas an abstract class can have both abstract and concrete methods.
d) None of the above

Correct answer is: c) An interface can only contain abstract methods, whereas an abstract class can have both abstract and concrete methods.

Python OOPS MCQ : Set 1

Python OOPS MCQ

1). Which of the following assertions most accurately sums up Python’s encapsulation?

a) It is a process of hiding the implementation details of a class.
b) It is a process of creating multiple instances of a class.
c) It is a process of defining attributes and methods in a class.
d) It is a process of converting data types in Python.

Correct answer is: a) It is a process of hiding the implementation details of a class.
Explanation: Encapsulation in Python refers to the bundling of data and methods within a class, allowing the implementation details to be hidden from the outside world.

2). Which of the following is an example of inheritance in Python?

a) A class inheriting properties from another class.
b) A class implementing an interface.
c) A class containing multiple methods.
d) A class accessing variables from a module.

Correct answer is: a) A class inheriting properties from another class.
Explanation: A fundamental aspect of object-oriented programming is inheritance. It allows a class to inherit attributes and methods from another class, known as the superclass or base class.

3). What is the purpose of the `super()` function in Python?

a) It is used to invoke a superclass’s method.
b) It is used to define class attributes.
c) It is used to create an instance of a class.
d) It is used to encapsulate class methods.

Correct answer is: a) It is used to invoke a superclass’s method.
Explanation: The `super()` function is used to call a method or access an attribute from the superclass within a subclass.

4). Which of the following is true about multiple inheritance in Python?

a) A class may descended from various superclasses.
b) Multiple classes can inherit from a single superclass.
c) A class can inherit from only one superclass.
d) Multiple classes cannot be used together in Python.

Correct answer is: a) A class may descended from various superclasses.
Explanation: Python supports multiple inheritance, which means a class can inherit attributes and methods from multiple parent classes.

5). What is the purpose of the `__init__` method in Python classes?

a) It is a special method used to create a new instance of a class.
b) It is used to define class attributes.
c) It is a built-in method that Python automatically calls.
d) It is used to delete an instance of a class.

Correct answer is: a) It is a special method used to create a new instance of a class.
Explanation: The `__init__` method, also known as the constructor, is called when a new instance of a class is created. The characteristics of the object are initialised using it.

6). What is the purpose of the `self` parameter in Python class methods?

a) It represents the superclass of a class.
b) It represents the current instance of a class.
c) It is a keyword used to define class attributes.
d) It is a built-in function in Python.

Correct answer is: b) It represents the current instance of a class.
Explanation: The `self` parameter is a reference to the current instance of a class. It is used to access and modify the object’s attributes and methods.

7). Which of the following best describes polymorphism in Python?
a) It allows a class to inherit from multiple superclasses.

b) It allows a class to hide its implementation details.
c) It allows different classes to implement the same method name.
d) It allows a class to access variables from a module.

Correct answer is: c) It allows different classes to implement the same method name.
Explanation: Polymorphism in Python refers to the ability of different classes to define the same method name but with different implementations.

8). What is method overriding in Python?

a) It allows a subclass to inherit attributes from a superclass.
b) It allows a subclass to implement its own version of a method inherited from a superclass.
c) It allows a subclass to access the private attributes of a superclass.
d) It allows a subclass to hide its implementation details.

Correct answer is: b) It allows a subclass to implement its own version of a method inherited from a superclass.
Explanation: The act of a subclass providing its own implementation of a method that is already defined in its superclass is known as method overriding.

9). What is the difference between class variables and instance variables in Python?

a) Class variables are defined within methods, while instance variables are defined outside methods.
b) Class variables are accessible only within the class, while instance variables are accessible outside the class.
c) Class variables have a different value for each instance of a class, while instance variables have the same value for all instances.
d) Class variables are used to define attributes, while instance variables are used to define methods.

Correct answer is: c) Class variables have a different value for each instance of a class, while instance variables have the same value for all instances.
Explanation: Class variables are shared among all instances of a class and have the same value, whereas instance variables have distinct values for each instance of a class.

10). Which of the following is an example of a composition relationship in Python?

a) A class inheriting properties from another class.
b) A class having an instance of another class as its attribute.
c) A class implementing an interface.
d) A class accessing variables from a module.

Correct answer is: b) A class having an instance of another class as its attribute.
Explanation: Composition is a relationship where a class contains an instance of another class as one of its attributes.

11). What is the difference between a class method and an instance method in Python?

a) Class methods can access instance attributes, while instance methods cannot.
b) Instance methods can access class attributes, while class methods cannot.
c) Class methods are defined using the `@classmethod` decorator, while instance methods are not.
d) Instance methods are called using the class name, while class methods are called using an instance of the class.

Correct answer is: b) Instance methods can access class attributes, while class methods cannot.
Explanation: Instance methods have access to both instance and class attributes, while class methods can only access class attributes.

12). What is the purpose of the `@staticmethod` decorator in Python?

a) It allows a method to be called without creating an instance of the class.
b) It converts a class method into an instance method.
c) It enables inheritance between classes.
d) It defines a method within a class.

Correct answer is: a) It allows a method to be called without creating an instance of the class.
Explanation: The `@staticmethod` decorator is used to define a static method in a class. Without creating an instance, static methods can be called on the class itself.

13). What is the role of an abstract base class (ABC) in Python?

a) It allows multiple inheritance.
b) It defines a base class that cannot be instantiated and provides a common interface for its subclasses.
c) It allows private access to class attributes.
d) It provides a mechanism for encapsulation.

Correct answer is: b) It defines a base class that cannot be instantiated and provides a common interface for its subclasses.
Explanation: An abstract base class in Python provides a common interface for its subclasses. It acts as a model for its subclasses but cannot be instantiated.

14). Which keyword is used to access the superclass from within a subclass in Python?

a) super
b) self
c) parent
d) base

Correct answer is: a) super
Explanation: The `super` keyword is used to access the superclass from within a subclass. It allows the subclass to invoke methods or access attributes of the superclass.

15). What is the purpose of the `__str__` method in Python classes?

a) It converts a class to a string representation.
b) It initializes the attributes of a class.
c) It defines the equality between two instances of a class.
d) It creates a deep copy of an instance.

Correct answer is: a) It converts a class to a string representation.
Explanation: The `__str__` method is used to define the string representation of a class. It is automatically called when the `str()` function is used on an instance of the class.

16). What is the difference between shallow copy and deep copy in Python?

a) Shallow copy copies only the references, while deep copy copies the actual values.
b) Shallow copy creates a new object, while deep copy creates a reference to the original object.
c) Shallow copy creates an independent copy of an object, while deep copy creates a nested copy.
d) Shallow copy only works for immutable objects, while deep copy works for both mutable and immutable objects.

Correct answer is: a) Shallow copy copies only the references, while deep copy copies the actual values.
Explanation: Deep copy generates a completely independent copy with its own values, whereas shallow copy creates a new object that references the values of the original object.

17). Which of the following is true about the `__del__` method in Python?

a) It is used to define class attributes.
b) It is automatically invoked whenever a class instance is generated.
c) It is a destructor method that is called when an instance is about to be destroyed.
d) It is used to initialize the attributes of a class.

Correct answer is: c) It is a destructor method that is called when an instance is about to be destroyed.
Explanation: The `__del__` method is a destructor method in Python. It is automatically called when an instance of a class is about to be destroyed.

18). What is the purpose of method overloading in Python?

a) It allows a method to have different implementations based on the number and types of arguments.
b) It allows a method to override another method from a superclass.
c) It allows a method to be called without passing any arguments.
d) It allows a method to be called from within another method.

Correct answer is: a) It allows a method to have different implementations based on the number and types of arguments.
Explanation: Method overloading in Python allows a method to have multiple implementations with different numbers and types of arguments.

19). Which of the following statements is true about method overriding in Python?

a) A subclass can override a method in its superclass.
b) A subclass can only override a private method in its superclass.
c) A subclass can override a method in any other class.
d) A subclass cannot override a method in its superclass.

Correct answer is: a) A subclass can override a method in its superclass.
Explanation: A subclass can offer its own implementation of a method that is already defined in its superclass by using method overriding.

20). What is the purpose of the `@property` decorator in Python?

a) It is used to define a class attribute.
b) It is used to define a static method.
c) It is used to create a read-only property with a getter method.
d) It is used to create a write-only property with a setter method.

Correct answer is: c) It is used to create a read-only property with a getter method.
Explanation: The `@property` decorator is used to define a getter method for creating a read-only property in a class.

21). What is abstraction?

a) The ability of an object to take on different forms
b) The process of one class inheriting the properties and methods of another class
c) The process of hiding the implementation details of an object from the user
d) The process of representing abstract concepts

Correct answer is: d) The process of representing abstract concepts
Explanation: Abstraction is one of the most important features of object-oriented programming. It allows for the creation of objects that represent things that do not have a physical representation in the real world. For example, a class can be used to represent the concept of a “person”, even though there is no such thing as a “person” in the real world.

22). What distinguishes a constructor from a method?

a) A constructor is a method that is called when an object of that class is created, while a method is a function that is associated with a class
b) A constructor is a method that is used to initialize the data members of an object, while a method is a function that is used to perform operations on an object
c) A constructor is a method that is called when an object of that class is deleted, while a method is a function that is called when an object of that class is modified
d) None of the above

Correct answer is: b) A constructor is a method that is used to initialize the data members of an object, while a method is a function that is used to perform operations on an object

Python Features and Its Contribution

Python, a popular high-level programming language,
has gained immense popularity over the years due to its simplicity, versatility, and extensive range of features. It has emerged as a go-to language for developers, data scientists, and AI enthusiasts. In this article, we will explore the various features of Python and its significant contributions to the world of programming.

Table of Contents

  1. Introduction to Python
  2. Readability and Simplicity
  3. Interpreted Language
  4. Dynamic Typing
  5. Object-Oriented Programming (OOP)
  6. Extensive Standard Library
  7. Cross-Platform Compatibility
  8. Easy Integration with Other Languages
  9. Large Community and Active Support
  10. Web Development with Python
  11. Data Science and Machine Learning
  12. Automation and Scripting
  13. Testing and Debugging
  14. Scalability and Performance
  15. Conclusion

Introduction to Python

Python, created by Guido van Rossum in the late 1980s, is a versatile and powerful programming language. It was designed with a focus on simplicity and readability, allowing developers to write clean and expressive code. Python follows an open-source philosophy, making it freely available for everyone to use and contribute to its development.

Readability and Simplicity

One of the remarkable features of Python is its emphasis on readability. Its syntax is clear, concise, and easy to understand, making it an ideal language for beginners. Python utilizes indentation to define code blocks, which enhances code readability and enforces good coding practices.

Interpreted Language

Python is an interpreted language, meaning that there is no need for compilation before execution. This feature enables developers to write code and immediately see the results, making the development process faster and more efficient.

Dynamic Typing

In Python, variables are dynamically typed, which means that the type of a variable is determined at runtime. This flexibility allows for more expressive coding and makes Python suitable for rapid prototyping and quick development cycles.

Object-Oriented Programming (OOP)

Python fully supports object-oriented programming, allowing developers to create reusable and modular code. It provides features like classes, objects, inheritance, and polymorphism, making it easy to build complex applications and maintain codebases efficiently.

Extensive Standard Library

Python comes with a vast standard library that provides a wide range of modules and functions for various purposes. This library eliminates the need to write code from scratch for common tasks, such as file handling, network programming, regular expressions, and more. The availability of these modules boosts productivity and speeds up the development process.

Cross-Platform Compatibility

Python is highly portable and can run on different operating systems, including Windows, macOS, Linux, and Unix. Developers can write code once and run it anywhere, making Python an excellent choice for cross-platform development.

Easy Integration with Other Languages

Python’s versatility extends to its ability to integrate with other programming languages seamlessly. It provides robust support for integrating code written in languages like C, C++, and Java, enabling developers to leverage existing codebases and libraries.

Large Community and Active Support

Python boasts a vibrant and active community of developers, who contribute to its growth and share their knowledge and expertise. The availability of extensive documentation, tutorials, and online forums ensures that developers can find answers to their questions and receive support promptly.

Web Development with Python

Python offers various frameworks, such as Django and Flask, that simplify web development tasks. These frameworks provide tools and libraries for handling web requests, managing databases.

creating interactive web applications. With Python, developers can build robust and scalable web solutions, ranging from simple websites to complex web applications.

Data Science and Machine Learning

Python has emerged as a dominant language in the field of data science and machine learning. Its rich ecosystem of libraries and frameworks, including NumPy, Pandas, and scikit-learn, provide powerful tools for data manipulation, analysis, and modeling. Python’s simplicity and ease of use make it an ideal choice for data scientists and machine learning practitioners to explore and analyze data, build predictive models, and deploy machine learning algorithms in real-world applications.

Automation and Scripting

Python excels in automation and scripting tasks. Its concise syntax and extensive library support allow developers to automate repetitive tasks, streamline workflows, and enhance productivity. Whether it’s automating file operations, performing system administration tasks, or building custom scripts, Python provides a versatile and efficient solution.

Testing and Debugging

Python offers robust testing and debugging capabilities, making it easier for developers to ensure the quality and reliability of their code. The built-in unit testing framework, along with third-party libraries like PyTest, simplifies the process of writing and executing tests. Python’s debugging tools, such as pdb and integrated development environments (IDEs) like PyCharm, facilitate efficient debugging and troubleshooting.

Scalability and Performance

While Python is renowned for its simplicity and ease of use, it also provides ways to improve performance and scalability. Integrating Python with high-performance libraries like NumPy and utilizing techniques such as code optimization and parallel processing can significantly enhance the execution speed of Python programs. Additionally, Python’s integration with languages like C and its support for multiprocessing enable developers to tackle computationally intensive tasks efficiently.

Conclusion

Python’s extensive range of features and its contributions to various domains have made it a preferred language for developers worldwide. Its simplicity, readability, and versatility, combined with its vast ecosystem of libraries and frameworks, empower developers to build robust applications, analyze data, automate tasks, and create innovative solutions. Whether you are a beginner or an experienced developer, Python offers a rich and rewarding programming experience.

FAQs (Frequently Asked Questions)

  1. Q: Is Python a beginner-friendly language? A: Yes, Python is known for its simplicity and readability, making it an excellent choice for beginners.
  2. Q: Can Python be used for web development? A: Absolutely! Python offers powerful web development frameworks like Django and Flask for building web applications.
  3. Q: What makes Python suitable for data science? A: Python’s extensive libraries, such as NumPy and Pandas, provide robust tools for data manipulation, analysis, and modeling.
  4. Q: Does Python support object-oriented programming? A: Yes, Python fully supports object-oriented programming, enabling developers to create reusable and modular code.
  5. Q: How can I contribute to the Python community? A: You can contribute to the Python community by participating in open-source projects, sharing your knowledge through tutorials or blog posts, and actively engaging in online forums and communities.
 

Python File Handling MCQ : Set 4

Python File Handling MCQ

1). What is the purpose of the following code?

				
					file = open('file.txt')
data = file.read().split()
m_num = []
for val in data:
    if val.isnumeric():
        if len(val) == 10:
            m_num.append(val)
print("Mobile numbers in the file: ", m_num)
				
			

a) Read the contents of the file and split them into a list
b) Extract all the numeric values from the file
c) Filter and collect 10-digit mobile numbers from the file
d) Print the content of the file

Correct answer is: c) Filter and collect 10-digit mobile numbers from the file
Explanation: The given code opens a file named ‘file.txt’ and reads its contents using the `read()` method. The content is then split into a list of individual words using the `split()` method. Next, an empty list `m_num` is created to store the mobile numbers. The code then iterates through each value in the list `data` and checks if it is a numeric value using the `isnumeric()` method. If the value is numeric, it further checks if its length is equal to 10 digits. If both conditions are met, the value is considered a 10-digit mobile number and is appended to the `m_num` list. Finally, the code prints the collected mobile numbers using the `print()` function. The purpose of this code snippet is to filter and extract 10-digit mobile numbers from the given file.

2). What is the purpose of the following code?

				
					file = open("file name", "r")
lines = file.readlines()
count = 0
for line in lines:
    count += 1
print("Total number of lines in the file: ", count)
				
			

a) To read the contents of a file and store them in a list
b) To count the number of characters in a file
c) To count the number of words in a file
d) To count the number of lines in a file

Correct answer is: d) To count the number of lines in a file
Explanation: The given code opens a file named “file name” in read mode using the `open()` function and assigns it to the `file` variable. Then, it uses the `readlines()` method to read all the lines from the file and stores them in a list called `lines`. Next, a variable `count` is initialized to 0. The code then iterates over each line in the `lines` list using a `for` loop. For each line, the `count` variable is incremented by 1, effectively counting the number of lines in the file. Finally, the total number of lines in the file is printed as output using the `print()` function.

3). What is the purpose of the following code?

				
					import os
info = os.stat('file.txt')
print("Size of the file: ", info.st_size)
				
			

a) To check if the file ‘file.txt’ exists in the current directory
b) To get the size of the file ‘file.txt’
c) To delete the file ‘file.txt’
d) To rename the file ‘file.txt’

Correct answer is: b) To get the size of the file ‘file.txt’
Explanation: The code uses the `os.stat()` function from the `os` module to retrieve the file information for the file named ‘file.txt’. The `os.stat()` function returns a named tuple with several attributes representing file information. In this case, the code accesses the `st_size` attribute of the `info` named tuple, which corresponds to the size of the file in bytes. The code then prints the size of the file to the console using the `print()` function. Therefore, the purpose of this code snippet is to obtain and display the size of the file ‘file.txt’.

4). What is the purpose of the following code?

				
					tup = ('1', '2', '3')
f = open('file.txt', 'w')
f.write(" ".join(tup))
f.close()
				
			

a) It creates a tuple containing three elements: ‘1’, ‘2’, and ‘3’.
b) It opens a file named ‘file.txt’ in write mode.
c) It writes the string representation of the tuple elements separated by a space to the file.
d) It closes the file after writing the data.

Correct answer is: c) It writes the string representation of the tuple elements separated by a space to the file.
Explanation: It creates a tuple named `tup` containing three elements: ‘1’, ‘2’, and ‘3’. It opens a file named ‘file.txt’ in write mode using the `open()` function with the mode parameter set to ‘w’. It writes the string representation of the elements in the tuple `tup` to the file by using the `write()` method. The elements are joined together using the `join()` method with a space as the separator. Finally, it closes the file using the `close()` method to ensure that all the changes are saved.

5). What is the purpose of the following code?

				
					f = open('file.txt','r')
print(f.closed)
f.close()
print(f.closed)
				
			

a) To open a file in read mode, check if the file is closed, and then close the file
b) To open a file in write mode, check if the file is closed, and then close the file
c) To open a file in append mode, check if the file is closed, and then close the file
d) To open a file in read mode and check if the file is closed, without closing the file

Correct answer is: a) To open a file in read mode, check if the file is closed, and then close the file
Explanation: The code opens a file named ‘file.txt’ in read mode using the `open()` function with the mode parameter set to ‘r’. The `print(f.closed)` statement is used to check the status of the file object’s `closed` attribute, which indicates whether the file is closed or not. Since the file is just opened, the output will be `False`. The `f.close()` statement is used to explicitly close the file. The `print(f.closed)` statement is called again to check the status of the file object’s `closed` attribute after closing the file. Since the file is closed, the output will be `True`.

6). What is the purpose of the following code?

				
					file = open('file.txt')
words = file.read().split()
list1 = []
for word in words:
    for char in word:
        list1.append(char)
print("Characters in the file in the list: ", list1)
				
			

a) To count the number of characters in a file.
b) To extract all the words from a file.
c) To create a list of characters from a file.
d) To concatenate all the words in a file.

Correct answer is: c) To create a list of characters from a file.
Explanation: The given code opens a file named ‘file.txt’ using the `open()` function without specifying a mode, which defaults to read mode (‘r’). It then reads the content of the file using the `read()` method and splits the content into a list of words using the `split()` method. The code initializes an empty list `list1` to store the characters from the file. It then iterates over each word in the `words` list and, for each word, iterates over each character using a nested loop. It appends each character to the `list1` using the `append()` method. Finally, it prints the message “Characters in the file in the list: ” followed by the `list1` containing all the characters from the file.

7). What is the purpose of the following code?

				
					data = data2 = ""
with open('file1.txt') as f:
    data = f.read()
with open('file2.txt') as f:
    data2 = f.read()
data += "\n"
data += data2

with open ('file3.txt', 'w') as f:
    f.write(data)
				
			

a) It reads the contents of two files and concatenates them.
b) It copies the contents of one file to another file.
c) It appends the contents of one file to another file.
d) It deletes the contents of two files and saves the result in another file.

Correct answer is: a) It reads the contents of two files and concatenates them.
Explanation: The given code snippet opens two files, ‘file1.txt’ and ‘file2.txt’, and reads their contents using the `read()` method. The contents of the two files are stored in the variables `data` and `data2` respectively. The code then appends a newline character (`”\n”`) to the `data` variable and concatenates the contents of `data2` to `data`. Finally, the code opens a file named ‘file3.txt’ in write mode using the `open()` function with the `’w’` argument. It writes the concatenated data to ‘file3.txt’ using the `write()` method, effectively saving the combined contents of ‘file1.txt’ and ‘file2.txt’ in ‘file3.txt’.

8). What is the purpose of the following code?

				
					file = open('file name')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.isalpha():
            count += 1
print("Total number of characters in the file: ", count)
				
			

a) Count the number of lines in the file.
b) Count the number of words in the file.
c) Count the number of alphabetic characters in the file.
d) Count the number of non-alphabetic characters in the file.

Correct answer is: c) Count the number of alphabetic characters in the file.
Explanation: The given code opens a file and reads its contents. It then splits the contents into words and initializes a counter, `count`, to zero. The code then iterates over each word and checks each character in the word. If the character is alphabetic (a letter), it increments the `count` by 1. Finally, it prints the total number of alphabetic characters in the file. Therefore, the purpose of this code is to count the number of alphabetic characters in the file.

9). What is the purpose of the following code?

				
					file = open('file.txt')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.isupper():
            count += 1
print("Total number of uppercase characters in the file: ", count)
				
			

a) Count the total number of words in the file.
b) Count the total number of lines in the file.
c) Count the total number of lowercase characters in the file.
d) Count the total number of uppercase characters in the file.

Correct answer is:
d) Count the total number of uppercase characters in the file.
Explanation: `file = open(‘file.txt’)`: This line opens the file named “file.txt” in the default mode (‘r’), creating a file object called `file`. `words = file.read().split()`: The `read()` method is used to read the content of the file, and `split()` is called to split the content into a list of words. The list of words is stored in the variable `words`. `count = 0`: A variable `count` is initialized to 0 to keep track of the number of uppercase characters. `for word in words:`: This starts a loop to iterate over each word in the `words` list. `for char in word:`: This nested loop iterates over each character in the current word. `if char.isupper():`: The `isupper()` method is called on each character to check if it is an uppercase character. If the condition in step 6 is `True`, the code increments the `count` variable by 1. After both loops complete, the code prints the total number of uppercase characters found in the file.

10). What is the purpose of the following code?

				
					file = open('file.txt')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.islower():
            count += 1
print("Total number of lowercase characters in the file: ", count)
				
			

a) Count the total number of characters in the file
b) Count the total number of words in the file
c) Count the total number of uppercase characters in the file
d) Count the total number of lowercase characters in the file

Correct answer is: d) Count the total number of lowercase characters in the file
Explanation: The given code opens a file named ‘file.txt’ and reads its content. The content is then split into individual words. The variable `count` is initialized to 0. Next, a nested loop iterates over each word and each character within the word. The `if` statement checks if the character is lowercase using the `islower()` method. If it is lowercase, the `count` variable is incremented. Finally, the code prints the total number of lowercase characters in the file using the `print()` statement.

11). What is the purpose of the following code?

				
					file = open('file name')
words = file.read().split()
count = 0
for word in words:
    for char in word:
        if char.isnumeric():
            count += 1
print("Total number of digits in the file: ", count)
				
			

a) Count the total number of words in the file.
b) Calculate the average word length in the file.
c) Determine the frequency of each digit in the file.
d) Count the total number of digits in the file.

Correct answer is: d) Count the total number of digits in the file.
Explanation: The given code opens a file using the ‘file name’ and reads its contents. It then splits the content into individual words and initializes a counter variable, `count`, to keep track of the number of digits found in the file. The code then iterates over each word in the file. For each word, it iterates over each character and checks if the character is numeric using the `isnumeric()` method. If a character is numeric, the counter `count` is incremented. Finally, the code prints the total number of digits found in the file. Therefore, the purpose of the code is to count the total number of digits in the file and display the result.

12). What is the purpose of the following code?

				
					file = open('file.txt')
file.readline()
print("Position of a cursor in the file: ", file.tell())
				
			

a) To open the file ‘file.txt’ in read mode
b) To open the file ‘file.txt’ in write mode
c) To read a line from the file ‘file.txt’
d) To print the current position of the file cursor

Correct answer is: d) To print the current position of the file cursor
Explanation: The given code opens a file named ‘file.txt’ using the `open()` function without specifying the mode, which defaults to read mode. The `file.readline()` method is then called to read a single line from the file. Finally, the `file.tell()` method is used to retrieve the current position of the file cursor, and it is printed using the `print()` function. The purpose of this code snippet is to determine and display the position of the file cursor within the file after reading a line.

13). What is the purpose of the following code?

				
					file = open('file.txt')
file.readline()
print("Position of a cursor in the file: ",file.tell())
file.seek(10)
print("Position of a cursor in the file: ",file.tell())
				
			

a) To open a file and read its contents line by line.
b) To retrieve the current position of the file cursor.
c) To move the file cursor to a specific position.
d) To print the contents of the file starting from a specific position.

Correct answer is: c) To move the file cursor to a specific position.
Explanation: The code opens a file named “file.txt” using the `open()` function. It then reads a single line from the file using the `readline()` method, although this line is not utilized further. The `tell()` method is used to retrieve the current position of the file cursor, which represents the byte offset from the beginning of the file. The code then uses the `seek()` method to move the file cursor to a specific position, in this case, position 10. Finally, the `tell()` method is called again to print the updated position of the file cursor. Therefore, the purpose of this code snippet is to demonstrate the movement of the file cursor to a specific position within the file.

14). What is the purpose of the following code?

				
					file = open('file.txt')
data = list(file.readlines())
for line in reversed(data):
    print(line)
				
			

a) To open a file and print its contents in reverse order.
b) To open a file and store its contents in a list.
c) To open a file and print its contents line by line.
d) To open a file and append its contents to an existing list.

Correct answer is: a) To open a file and print its contents in reverse order.
Explanation: The given code snippet opens a file named ‘file.txt’ using the `open()` function and assigns it to the variable `file`. It then reads the contents of the file using the `readlines()` method and converts it into a list by using the `list()` function. The list of lines is stored in the variable `data`. The subsequent for loop iterates over the `data` list in reverse order using the `reversed()` function. Inside the loop, each line is printed using the `print()` function. As a result, the code prints the contents of the ‘file.txt’ file in reverse order, displaying each line on a separate line of the output.

15). What is the purpose of the following code?

				
					file = open('file name')
words = file.read().split()
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
count = 0
for word in words:
    for char in word:
        if char in vowels:
            count += 1
print("Total number of vowels in the file: ", count)
				
			

a) Count the total number of words in a file
b) Count the total number of lines in a file
c) Count the total number of vowels in a file
d) Count the total number of consonants in a file

Correct answer is: c) Count the total number of vowels in a file
Explanation: The code begins by opening a file using the `open()` function and assigning it to the `file` variable. The file name is specified as `’file name’` (please note that the actual file name would be provided in place of `’file name’`). The `file.read()` method is used to read the entire contents of the file as a single string. The `split()` method is then called on the string obtained from `file.read()` to split it into a list of words. By default, it splits the string at whitespace characters. The code initializes a list called `vowels` containing all the vowels in both lowercase and uppercase.A variable called `count` is initialized to 0. This variable will be used to keep track of the number of vowels encountered.The code then iterates over each word in the `words` list using a nested loop. Within the nested loop, each character in the current word is checked to see if it is present in the `vowels` list. If a character is found in the `vowels` list, it means it is a vowel, and the `count` variable is incremented by 1.Finally, the total number of vowels found in the file is printed using the `print()` function.

16). What is the purpose of the following code?

				
					file = open('file.txt')
words = file.read().split()
for word in words:
    if len(word) < 5:
        print(word, end=" ")
				
			

a) Open a file named ‘file.txt’ and read its content.
b) Open a file named ‘file.txt’ and write to it.
c) Count the number of words in a file named ‘file.txt’.
d) Print all words from a file named ‘file.txt’ that have a length less than 5.

Correct answer is: d) Print all words from a file named ‘file.txt’ that have a length less than 5.
Explanation: The code opens a file named ‘file.txt’ using the `open()` function and reads its content. The content is then split into a list of words using the `split()` method. The code then iterates over each word in the list and checks if its length is less than 5 characters. If a word satisfies the condition, it is printed using the `print()` function with the `end` parameter set to a space character. Therefore, the code’s purpose is to print all words from the file ‘file.txt’ that have a length less than 5.

17). What is the purpose of the following code?

				
					f1 = open("file.txt", "r")
data = f1.read()
data = data.replace(" ", "_")
f2 = open("file1.txt", "w")
f2.write(data)
				
			

a) Count the number of spaces in a text file and replace them with underscores.
b) Open a file named “file.txt” in read mode, replace all spaces with underscores, and save the modified content in a new file named “file1.txt”.
c) Open a file named “file.txt” in write mode, replace all underscores with spaces, and save the modified content in the same file.
d) Read the content of a file named “file.txt” and write it to a new file named “file1.txt” without any modifications.

Correct answer is: b) Open a file named “file.txt” in read mode, replace all spaces with underscores, and save the modified content in a new file named “file1.txt”.
Explanation: Opens a file named “file.txt” in read mode using the `open()` function and assigns it to the variable `f1`. Reads the entire content of the file using the `read()` method and stores it in the variable `data`. Replaces all occurrences of spaces with underscores in the `data` string using the `replace()` method. Opens a new file named “file1.txt” in write mode using the `open()` function and assigns it to the variable `f2`. Writes the modified `data` string to the “file1.txt” file using the `write()` method.