Python Variable MCQ : Set 4

Python Variable MCQ

1). What is the output of the following code?
x = [1, 2, 3]
y = x.copy()
y[0] = 10
print(x)

a) [1, 2, 3]
b) [10, 2, 3]
c) [1, 2, 3, 10]
d) None of these

Correct answer is a)
Explanation: The copy() method creates a shallow copy of the list. Modifying the copy does not affect the original list.

2). What is the output of the following code?
x = “Hello”
print(len(x))

a) 5
b) 6
c) 10
d) None of these

Correct answer is a)
Explanation: The len() function in Python returns the length of a string. In this case, len(“Hello”) is equal to 5.

3). Which of the following is the correct way to declare a global variable “x” inside a function?
a) global x
b) x = global
c) x.global()
d) None of these

Correct answer is a)
Explanation: The “global” keyword is used to declare a variable as global inside a function.

4). What is the output of the following code?
x = “Python”
print(x[-2])

a) t
b) o
c) n
d) None of these

Correct answer is a)
Explanation: Negative indexing starts from the end of the string. x[-2] returns the second-to-last character, which is “t”.

5). What is the output of the following code?
x = “Hello”
print(x[::-1])

a) Hello
b) olleH
c) ello
d) None of these

Correct answer is b)
Explanation: The slicing [::-1] reverses the string. In this case, “Hello” reversed becomes “olleH”.

6). Which of the following is a valid way to check if a variable “x” is of type float?
a) type(x) == float
b) x.type() == float
c) typeof(x) == float
d) None of these

Correct answer is a)
Explanation: The type() function is used to check the type of a variable. The comparison “type(x) == float” checks if “x” is of type float.

7). What will be the value of the variable “x” after the execution of the following code?
x = [1, 2, 3]
y = x
y.append(4)

a) [1, 2, 3]
b) [1, 2, 3, 4]
c) [4, 3, 2, 1]
d) None of these

Correct answer is b)
Explanation: Both variables “x” and “y” refer to the same list object. Modifying “y” will also modify “x” since they point to the same memory location.

8). What is the output of the following code?
x = “Hello”
print(x[1])

a) H
b) e
c) l
d) None of these

Correct answer is b)
Explanation: Indexing starts from 0. x[1] returns the second character, which is “e”.

9). Which of the following is true about local variables in Python?
a) They can be accessed from any part of the program
b) Their scope is limited to the function or block where they are defined
c) They are declared using the local keyword
d) None of these

Correct answer is b)
Explanation: Local variables are only accessible within the function or block where they are defined.

10). What is the output of the following code?
x = 2
y = 3
print(x < y)

a) True
b) False
c) 2
d) 3

Correct answer is a)
Explanation: The < operator checks if the left operand is less than the right operand. In this case, 2 < 3 is True.

11). What is the output of the following code?
x = 5
y = 2
z = x % y
print(z)

a) 1
b) 2
c) 0
d) None of these

Correct answer is a)
Explanation: The % operator calculates the remainder of the division. In this case, 5 % 2 is equal to 1.

12). Which of the following is a valid variable name in Python?
a) 1_variable
b) variable_1
c) variable-1
d) variable 1

Correct answer is b)
Explanation: Variable names in Python can contain letters, numbers, and underscores, but they cannot start with a number or contain spaces or hyphens.

13). What is the output of the following code?
x = “Python”
print(x[1:4])

a) Pyt
b) yth
c) tho
d) None of these

Correct answer is b)
Explanation: Slicing extracts a portion of a string. In this case, x[1:4] returns the characters from index 1 to index 3, excluding the character at index 4.

14). Which of the following is the correct way to convert a floating-point number to an integer in Python?
a) int()
b) float_to_int()
c) str()
d) None of these

Correct answer is a)
Explanation: The int() function can be used to convert a floating-point number to an integer in Python.

15). What will be the value of the variable “x” after the execution of the following code?
x = 5
y = x
y = y + 2
print(x)

a) 5
b) 7
c) 2
d) None of these

Correct answer is a)
Explanation: Assigning the value of “x” to “y” creates a copy of the value. Modifying “y” does not affect the original value of “x”.

16). What is the output of the following code?
x = “Python”
print(x[1:])

a) Python
b) ython
c) P
d) None of these

Correct answer is b)
Explanation: Slicing with an omitted end index returns the substring from the start index to the end of the string. In this case, x[1:] returns “ython”.

17). Which of the following is the correct way to declare a constant variable in Python?
a) Use the const keyword
b) Prefix the variable name with an underscore (e.g., _PI)
c) Use all uppercase letters for the variable name (e.g., PI)
d) None of these

Correct answer is c)
Explanation: Although Python does not have built-in support for constant variables, using all uppercase letters for the variable name is a common convention to indicate that it should be treated as a constant.

18). What is the output of the following code?
x = [1, 2, 3]
y = x
y = [4, 5, 6]
print(x)

a) [1, 2, 3]
b) [4, 5, 6]
c) [1, 2, 3, 4, 5, 6]
d) None of these

Correct answer is a)
Explanation: Assigning a new list [4, 5, 6] to “y” does not modify the original list object referred to by “x”.

19). Which of the following is a valid way to concatenate two strings in Python?
a) str.add()
b) str.join()
c) str.append()
d) None of these

Correct answer is b)
Explanation: The str.join() method can be used to concatenate two strings in Python.

20). What will be the output of the following code?
x = 2
y = 3
print(x == y)

a) True
b) False
c) 2
d) 3

Correct answer is b)
Explanation: The == operator checks if the left operand is equal to the right operand. In this case, 2 is not equal to 3, so the expression evaluates to False.

21). What is the output of the following code?
x = 2
x = x * 3
x = x + 1
print(x)

a) 5
b) 7
c) 8
d) 9

Correct answer is d)
Explanation: The code multiplies the value of “x” by 3, adds 1 to it, and assigns the result back to “x”. Therefore, the value of “x” becomes 7, then 8.

22). What will be the value of the variable “y” after the execution of the following code?
x = [1, 2, 3]
y = x
x.append(4)
print(y)

a) [1, 2, 3]
b) [1, 2, 3, 4]
c) [4, 3, 2, 1]
d) None of these

Correct answer is b)
Explanation: When “y” is assigned the value of “x”, it refers to the same list object in memory. Therefore, any changes made to the list through either variable will be reflected in both. The code appends the value 4 to the list, so the value of “y” becomes [1, 2, 3, 4].

23). What will be the value of the variable “x” after the execution of the following code?
x = [1, 2, 3]
y = x
y[0] = 4
print(x)

a) [1, 2, 3]
b) [4, 2, 3]
c) [4, 2, 3, 4]
d) None of these

Correct answer is b)
Explanation: Since “x” and “y” refer to the same list object, modifying the list through one variable will affect the other. The code changes the value at index 0 to 4, so the value of “x” becomes [4, 2, 3].

24). What is the output of the following code?
x = “Hello”
y = “World”
z = x + y
print(z)

a) “Hello World”
b) “HelloWorld”
c) “WorldHello”
d) “HWeolrllod”

Correct answer is a)
Explanation: The + operator in Python can be used to concatenate two strings in Python. In this case, the variable “z” contains the concatenation of “Hello” and “World”, resulting in the string “Hello World”.

25). Which of the following statements is true regarding variable names in Python?
a) Variable names can contain spaces.
b) Variable names can start with a number.
c) Variable names are case-insensitive.
d) Variable names can contain special characters like @ or #.

Correct answer is b)
Explanation: Variable names in Python cannot start with a number. They can only start with a letter or an underscore.

Python Variable MCQ : Set 3

Python Variable MCQ

1). What will be the value of the following variable?
a = 10
a += 5
a -= 3

a) 5
b) 7.5
c) 10
d) 12

Correct answer is d)
Explanation: The code performs arithmetic operations on the variable “a”. The final value of “a” will be 12.

2). What is the scope of a local variable in Python?
a) Restricted to the function where it is defined
b) Accessible from any part of the program
c) Restricted to the class where it is defined
d) None of these

Correct answer is a)
Explanation: A local variable is accessible only within the function or block of code where it is defined.

3). Which of the following statements is true about global variables in Python?
a) They are accessible only within a specific function
b) They can be accessed from any part of the program
c) They can only store numeric values
d) None of these

Correct answer is b)
Explanation: Global variables can be accessed from any part of the program, including functions.

4). What will be the output of the given code?
a = 7
b = 3
print(x // y)

a) 2.5
b) 2
c) 3
d) 2.0

Correct answer is b)
Explanation: The double slash (//) is the floor division operator, which performs integer division and returns the quotient. In this case, 5 // 2 is equal to 2.

5). What is the data type of the following variable?
x = 5.0

a) int
b) float
c) double
d) None of these

Correct answer is b)
Explanation: The variable “x” is assigned a floating-point value, so its data type is float.

6). What will be the output of the given code?
x = “2”
y = 3
print(x * y)

a) 23
b) 6
c) 222
d) TypeError

Correct answer is c)
Explanation: When a string is multiplied by an integer, it repeats the string multiple times. In this case, “2” * 3 results in “222”.

7). What will be the output of the given code?
x = 10
y = “20”
print(x + int(y))

a) 30
b) 1020
c) 102010
d) TypeError

Correct answer is a)
Explanation: The code converts the string “20” to an integer using the int() function and performs addition. The result is 30.

8). Which of the following is an invalid variable name in Python?
a) my-var
b) my_var
c) 123var
d) _var123

Correct answer is a)
Explanation: Variable names cannot contain hyphens (-) in Python. Underscores (_) are allowed.

9). What will be the value of the variable “x” after the execution of the following code?
x = 5
x = x + “2”

a) 7
b) 52
c) TypeError
d) None of these

Correct answer is c)
Explanation: You cannot concatenate a string and an integer using the + operator. It raises a TypeError.

10). Which of the following is the correct way to check the type of a variable “x”?
a) typeof(x)
b) type(x)
c) x.type()
d) None of these

Correct answer is b)
Explanation: The type() function is used to check the type of a variable in Python.

11). What is the output of the following code?
x = 3.8
print(int(x))

a) 3
b) 4
c) 3.0
d) 4.0

Correct answer is a)
Explanation: The int() function converts a floating-point number to an integer by truncating the decimal part. In this case, int(3.8) is equal to 3.

12). What will be the output of the following code?
x = “Hello, World!”
print(x[7:12])

a) Hello
b) World
c) , Wor
d) None of these

Correct answer is b)
Explanation: The code uses slicing to extract the characters from index 7 to 11 (exclusive). This results in the string “World”.

13). Which of the following is true about constant variables in Python?
a) Their values cannot be changed after the assignment
b) They can only store integer values
c) They are declared using the const keyword
d) None of these

Correct answer is d)
Explanation: Python does not have a built-in concept of constant variables. Variables can be reassigned with different values.

14). What will be the output of the following code?
x = 2
y = 3
print(x ** y)

a) 6
b) 8
c) 9
d) 6.0

Correct answer is c)
Explanation: The double asterisk (**) is the exponentiation operator in Python. In this case, 2 ** 3 is equal to 8.

15). Which of the following is an immutable data type in Python?
a) list
b) tuple
c) dictionary
d) set

Correct answer is b)
Explanation: Tuples are immutable, meaning their elements cannot be changed once assigned. Lists, dictionaries, and sets are mutable.

16). What is the output of the following code?
x = “SQATOOLS”
print(x[-3:])

a) OLS
b) LS
c) SQA
d) OOLS

Correct answer is a)
Explanation: Negative indexing starts from the end of the string. x[-3:] extracts the last three characters, resulting in “OLS”.

17). What will be the value of the variable “x” in the given code?
x = 2
x = x * x

a) 2
b) 4
c) 8
d) None of these

Correct answer is b)
Explanation: The code squares the value of “x” and assigns the result back to “x”. So the value of “x” is 4.

18). Which of the following is a valid way to concatenate two strings in Python?
a) str1.add(str2)
b) str1 + str2
c) str1.concat(str2)
d) None of these

Correct answer is b)
Explanation: The + operator in Python is used to concatenate two strings in Python.

19). What is the output of the given code?
x = “Python”
print(x[1:4])

a) Pyt
b) yth
c) thon
d) None of these

Correct answer is b)
Explanation: The code uses slicing to extract the characters from index 1 to 3 (exclusive). This results in the string “yth”.

20). What will be the output of the given code?
x = 5
y = 2
print(x % y)

a) 2.5
b) 2
c) 1
d) 2.0

Correct answer is c)
Explanation: The % operator is the modulus operator, which returns the remainder of the division. In this case, 5 % 2 is equal to 1.

21). Which of the following is a valid way to convert an integer to a string in Python?
a) int_to_str()
b) str()
c) convert_str()
d) None of these

Correct answer is b)
Explanation: The str() function is used to convert an object to its string representation.

22). What is the output of the following code?
x = 2.7
print(round(x))

a) 2
b) 3
c) 2.0
d) 3.0

Correct answer is a)
Explanation: The round() function rounds the given number to the nearest integer. In this case, round(2.7) is equal to 2.

23). What will be the value of the variable “x” after the execution of the following code?
x = [1, 2, 3]
y = x
y[0] = 10

a) [1, 2, 3]
b) [10, 2, 3]
c) [10, 2, 3, 1]
d) None of these

Correct answer is b)
Explanation: Both variables “x” and “y” refer to the same list object. Modifying “y” will also modify “x” since they point to the same memory location.

24). Which of the following is a valid way to convert a string to an integer in Python?
a) int_to_str()
b) str()
c) int()
d) None of these

Correct answer is c)
Explanation: The int() function is used to convert a string to an integer in Python.

25). What is the output of the following code?
x = “Hello”
y = “World”
print(x + y)

a) HelloWorld
b) Hello World
c) Hello+World
d) None of these

Correct answer is a)
Explanation: The + operator concatenates two strings. In this case, “Hello” + “World” results in “HelloWorld”.

Python Variable MCQ : Set 2

Python Variable MCQ

1). What will be the output of the following Python code?
type(10.0)
  a) <class ‘float’>
  b) <class ‘int’>
  c) <class ‘list’>
  d) None of these

Correct answer is a).
Explanation: The value 10.0 is float, so the output of the given code will be <class ‘float’>.

2). What will be the output of the following Python code?
type(10/2)
  a) int
  b) <class ‘float’>
  c) 5
  d) None of these

Correct answer is b).
Explanation: Here, we are not finding the arithmetic value of 10/5, instead we need the data type of 10/5 (i.e. 2.0). So the output will be float.

3). What will be the output of the following Python code?
type(()) is <class ‘tuple’>
  a) True
  b) False

Correct answer is a).
Explanation: Tuples are stored inside round brackets () and the parameter inside type() is an empty tuple. So, the given code on execution will give the output as True.

4). What will be the output of the following Python code?
type([])
  a) <class ‘array’>
  b) <class ‘dict’>
  c) <class ‘list’>
  d) Code will generate an error

Correct answer is c).
Explanation: Lists are stored inside square brackets [] and the parameter inside type() is an empty list. So, the given code on execution will give the output as <class ‘list’>.

5). What will be the output of the following Python code?
type({}) is <class ‘set’>

  a) True
  b) False

Correct answer is b).
Explanation: type({}) produces a dictionary and not a set so the correct answer is b).

6). What will be the output of the following Python code?

bool(-5)
  a) True
  b) False

Correct answer is a).
Explanation: Bool is used to get a truth value of an expression.

7). A variable should be assigned a value before it is declared.
  a) True
  b) False

Correct answer is b).
Explanation: Python determines the type of a variable during runtime based on the value that is assigned to it. So, not necessary to assign a value during its declaration.

8). Which of the following function gives a unique number assigned to an object?
  a) ref()
  b) reference()
  c) id()
  d) type()

Correct answer is c).
Explanation: id() function returns a unique id for the object.

9). How do we define a block of code in Python?
  a) Using curly braces
  b) Indentation
  c) Using Brackets
  d) None of these

Correct answer is b).
Explanation: Identation is used to define a block of code in Python. Curly braces {} are used to define a block of code in other languages like C, C++,.

10). Variable names are case-sensitive in Python.
  a) True
  b) False

Correct answer is a).
Explanation: Variable names are case-sensitive in Python. So, variable1 is different than VARIABLE1 in Python.

11). How do we comment in a single line in Python?
  a) /
  b) \
  c) #
  d) ” “

Correct answer is c).
Explanation: Hash (#) is used to comment the entire line.

12). The following way is correct to assign multiple variables to a single value
      a = b = c = 5
  a) True
  b) False

Correct answer is a).
Explanation: This is a compact way to assign the same value to multiple variables. Here, a, b, and c will have a value of 5.

13). The following way is correct to assign multiple variables to multiple values
a, b, c = “Bikes”, “Cars”, “Trucks”
  a) True
  b) False

Correct answer is a).
Explanation: This is a compact way to assign values to multiple variables. Here, a, b, and c will have “Bikes”, “Cars”, and “Trucks” respectively.

14). What will be the output of the following Python code?
type(4j)
  a) alphanum
  b) long
  c) complex
  d) Error

Correct answer is c).
Explanation: j suffix to 4 (e.g., 4j) indicates the imaginary part. Type for such value returns complex.

15). What will be the output of the following Python code?
type(4l)
  a) alphanum
  b) long
  c) complex
  d) Error

Correct answer is d)
Explanation: Output will produce an error for this Python code. It varies on Python versions. This is valid in Python 2.7.5 and returns “long”.

16). Python supports the conversion of integer variables to complex.
  a) True
  b) False

Correct answer is a).
Explanation: Conversion of integer say x to complex is supported in Python using complex (x) function.

17). Python supports the conversion of complex variables to integers.
  a) True
  b) False

Correct answer is b).
Explanation: Conversion of complex numbers to integers is not supported in Python.

18). What will be the output of the following Python code?
var = “Hello”
int(var)
  a) Hello
  b) H,e,l,l,o
  c) Code will generate an error
  d) None of these

Correct answer is c).
Explanation: This is not supported in Python, and the code will generate an error: invalid literal for int() with base 10.

19). What will be the output of the following Python code?
var = “1234”
int(var)
  a) 1234
  b) 1,2,3,4
  c) Code will generate an error
  d) None of these

Correct answer is a).
Explanation: This will work fine in Python, and the code will produce output 1234 (correct option a).

20). What will be the output of the following Python code?
var = str(1234)
print(var)
  a) 1234
  b) 1,2,3,4
  c) ‘1234’
  d) Code will generate an error

Correct answer is a).
Explanation: This will work fine in Python, and the code will produce output 1234 (correct option a).

21). What will be the output of the following Python code?
str(1234)
  a) 1234
  b) 1,2,3,4
  c) ‘1234’
  d) Code will generate an error

The correct answer is c).
Explanation: This will work fine in Python, and the code will produce output ‘1234’ (correct option c).

22). What is a variable in Python Programming language?
a) A container to store data
b) A function to perform calculations
c) A loop control structure
d) None of these

Correct answer is a)
Explanation: A variable in Python is a name that refers to a value or data stored in the computer’s memory.

23). Which of the following is a valid variable name in Python?
a) 123var
b) var123
c) _var
d) None of these

Correct answer is b)
Explanation: Variable names in Python can start with a letter or an underscore (_), but not with a digit.

24). What will be the output of the following code?
x = 5
y = “Hello”
z = x + y
print(z)

a) 5Hello
b) Hello5
c) TypeError
d) None of these

Correct answer is c)
Explanation: You cannot perform arithmetic operations between different data types. Adding an integer and a string raises a TypeError.

25). Which of the following is not a valid variable type in Python?
a) int
b) float
c) string
d) char

Correct answer is d)
Explanation: Python does not have a separate data type for characters. Characters are represented as strings of length 1.

Python variable MCQ : Set 1

Python Variable MCQ

1). Which is the correct way to get the type of the variable, say for variable x that holds any kind of value?

  a) typedef (x)
  b) pytype (x)
  c) type (x)
  d) None of these

Correct answer is c).
Explanation: Type is a built-in function in Python that returns the class type of the object.
For example: If x is a number (integer), then type(x) will return “<class ‘int’>”.

2). Which is true for the variable names in Python?
  a) underscore is not allowed
  b) only names and special characters are allowed
  c) unlimited length
  d) none of these

Correct answer is c).
Explanation: There is no limit of the variable name length in the python.

3). What is __name__ in python?
  a) this is not a built-in variable
  b) this is a built-in variable
  c) None of these

Correct answer is b).
Explanation:  __name__ is a special or built-in variable that gives the name of the current module.

4). What is a ++ in Python?
  a) this is an increment operator like Java or C++
  b) this is not allowed in Python
  c) this is used as a global variable
  d) none of these

Correct answer is b).
Explanation: There is no ++ incremental operator in Python.

5). What are nonlocal variables in Python?
  a) Those are the same as the global variable
  b) Those are declared within nested functions
  c) There is no way to create nonlocal variables in Python
  d) None of these

Correct answer is b).
Explanation: Variables that are declared within a nested function are called nonlocal variables.

6). What are local variables in Python?
  a) Those are declared inside the function
  b) Those are defined within the local scope
  c) Not accessible outside of the function
  d) All of the these

Correct answer is d).
Explanation: Local variables are defined within a local scope, declared inside the function, and can not be accessed outside of the function.

7). Which is an invalid statement?
  a) testvar = 1000
  b) test var = 1000 2000
  c) test,var = 1000, 2000
  d) test_var = 1000

Correct answer is b).
Explanation: Whitespace is not allowed in the variable name.

8). What will be the value of variable b after the below code execution?
       a = “10”
       b = a + str (5)

  a) 15
  b) 5
  c) 105
  d) Syntax error

Correct answer is c).
Explanation: In this code, we are not adding 5 with 10 arithmetically but, we are adding two strings namely “10” and “5”.

9). Which is not a correct way to assign value to the variable?
  a) x=y=z=10
  b) x,y,z=10
  c) x,y,z=7.5,word,5
  d) None of these

Correct answer is b).
Explanation: Assigning a single value to multiple variables is not possible.

10). What will be the output of :
num = 2.789
print(round(num))
  a) 2.0
  b) 2.79
  c) 3.0
  d) 3

Correct answer is c)
Explanation: The round() function in Python rounds a number to the nearest whole number. In this case, num is 2.789, which is closer to 3 than to 2. Therefore, when you use round(num), it will round up to 3.0.

11). Python Variable must be declared before it is assigned a value:

  a) True
  b) False

Correct answer is b).
Explanation: No need to declare a variable before it is assigned a value

12). What are the things inside the list called?
  a) variables
  b) identifiers
  c) elements
  d) items

Correct answer is c).
Explanation: The things inside the list are called elements.

13). Identify the correct key value pair:
dict = {“Name”:”Rahul”, “Age”:24, “Occupation”:”Lawyer”}
  a) Key is Rahul, Value is Name
  b) Key is Name, Value is 24
  c) Key is Name, Value is Rahul
  d) Key is Name, Value is Age

Correct answer is c).
Explanation: Here, we are asked to identify the correct key value PAIR, so it will be option c).

14). Choose the correct option of the below code:

        def num():
             global a
             a = 20
             a = a+10
             print(a)

        a=10
        num()
        print(a)

  a) 30
       10

  b) 30
       30

  c) 20
       10

  d) 20
       20

Correct answer is b).
Explanation: Inside function num(), variable “a” is initially declared as global and assigned value as 20. Value of “a” will be printed when num() is called.
Variable inside the function will be given preference and hence the output of a will be a = a+10 = 20+10 = 30.
As we have declared “a” as global so when the function ends, outside print(a) will also output 30. So the correct answer is b).

15). What will be the output of the following code:
print(20//7)
  a) 2
  b) 2.0
  c) 2.857142857142857
  d) 3

Correct answer is a).
Explanation: The ‘//’ operator is called the floor division operator. This operator carries out the division and rounds off the value into the nearest whole number.

16). Which of the following is a core data type?
  a) boolean
  b) class
  c) def
  d) none of these

Correct answer is a).
Explanation: Boolean is a core data type.

17). Which of the following is an immutable data type?
  a) Sets
  b) Lists
  c) Strings
  d) Dictionary

Correct answer is c).
Explanation: Strings are an immutable data type as their values cannot be updated.

18). Which of the following is not a data type?
  a) String
  b) Character
  c) Integer
  d) None of these

Correct answer is b).
Explanation: Character is not a data type.

19). Which of the following function does not return any value?
  a) type
  b) int
  c) bool
  d) None

Correct answer is d).
Explanation: type, int, and bool return some value whereas the None function does not.

20). What will be the output of the following Python code?
type(“abcd”)
  a) string
  b) char
  c) str
  d) int

Correct answer is c).
Explanation: “abcd” is stored in a string format so it will return str.

21). What will be the output of the following code?
list1 = [1,2,3,4]
tup1 = tuple(list1)
print(tup1)
  a) [1,2,3,4]
  b) (1,2,3,4)
  c) 1 2 3 4
  d) The code will give an error while running

Correct answer is b).
Explanation: In this code, we are converting a list into a tuple and then printing it, so the output that we will get will be in tuple format.

22). In which of the following data type is stored in “Key – Value” pair format?
  a) Lists
  b) Dictionary
  c) Tuples
  d) None of these

Correct answer is b).
Explanation: In dictionaries, data is stored in key-value pair format.

23). Which of the following cannot be a variable?
  a) pass
  b) fail
  c) Both a and b
  d) None of these

Correct answer is a).
Explanation: pass is a keyword in Python. So, it can’t be a variable.

24). What will be the output of the following Python code?
type(range(10))
  a) <class ‘range’>
  b) int
  c) dict
  d) None of these

Correct answer is a).
Explanation: Range allows to generation a series of numbers within the mentioned range. If it’s used with type(), then it returns <class ‘range’>.

25). What will be the output of the following Python code?
type(‘5’)
  a) <class ‘str’>
  b) <class ‘int’>
  c) <class ‘float’>
  d) None of these

Correct answer is a).
Explanation: As ‘5’ is stored in a string format i.e. inside the colons (”), it will give the output as <class ‘str’>.

48. Problem to create an inheritance example in Python

In this Python oops program, we will create an inheritance example in Python. Python class called Dog that inherits from the Animal class.

Inheritance example in Python

Steps to solve the program
  1. The Dog class extends the Animal class, which means it inherits the properties and methods of the Animal class.
  2. The Dog class has its own constructor method __init__ that takes four parameters: name, color, breed, and weight. It calls the constructor of the Animal class using super() to initialize the name and color properties inherited from the Animal class. It also initializes two additional properties: self.breed to store the breed of the dog and self.weight to store the weight of the dog.
  3. The Dog class overrides the print_details method inherited from the Animal class. It calls the print_details method of the Animal class using super().print_details() to print the name and color of the dog. Then, it prints the additional details: breed and weight.
  4. The code creates an object dog of the Dog class by calling its constructor with the arguments “Jelly”, “Golden”, “Golden Retriever”, and 25.
  5. The print_details method is called on the dog object to print the details of the dog, including the inherited name and color, as well as the breed and weight specific to the Dog class.
  6. Thus, we have created an inheritance example in Python.
				
					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("Jelly", "Golden", "Golden Retriever", 25)
dog.print_details()
				
			

Output:

				
					Name: Jelly
Color: Golden
Breed: Golden Retriever
Weight: 25
				
			

Related Articles

Create a Python class called Animal with attributes name and color.

47. Problem to create an inheritance example in Python

In this Python oops program, we will create an inheritance example in Python. Python class called Animal with attributes name and color.

Inheritance example in Python

Steps to solve the program
  1. The Animal class has a constructor method __init__ that takes two parameters: name and color. It initializes two instance variables: self.name to store the name of the animal and self.color to store the color of the animal.
  2. The class also has a print_details method that prints the name and color of the animal.
  3. The code creates an object animal of the Animal class by calling its constructor with the arguments “Lion” and “Golden”.
  4. The print_details method is called on the animal object to print the details of the animal.
  5. Thus, we have creates an inheritance example in Python.
				
					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()
				
			

Output:

				
					Name: Lion
Color: Golden
				
			

Related Articles

Create a Python class called ShoppingCart with attributes items and total_cost.

Create a Python class called Dog that inherits from the Animal class.

46. Problem to create a Python class example

In this Python oops program, we will create a Python class example. Python class called ShoppingCart with attributes items and total_cost.

Python class example

Steps to solve the program
  1. The ShoppingCart class has a constructor method __init__ that initializes two instance variables: self.items as an empty list to store the items in the cart, and self.total_cost as 0 to track the total cost of the items.
  2. The class also has three methods:
  3. The add_item method takes item and cost as parameters and appends the item to the self.items list and adds the cost to the self.total_cost.
  4. The remove_item method takes item and cost as parameters and removes the item from the self.items list if it exists and subtracts the cost from the self.total_cost.
  5. The calculate_total_cost method returns the self.total_cost, representing the total cost of the items in the cart.
  6. The code creates an object cart of the ShoppingCart class by calling its constructor without any arguments.
  7. The add_item method is called three times on the cart object to add three items: “Shirt” with a cost of 250, “Pants” with a cost of 500, and “Shoes” with a cost of 1000.
  8. The remove_item method is called on the cart object to remove the “Shirt” item with a cost of 250.
  9. The calculate_total_cost method is called on the cart object to calculate the total cost of the items in the cart, and the result is assigned to the total_cost variable.
  10. Finally, the contents of the cart are printed using cart.items, and the total cost is printed using total_cost.
  11. Thus, we have created Python class example.
				
					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)
				
			

Output:

				
					Items in cart: ['Pants', 'Shoes']
Total Cost: 1500
				
			

Related Articles

Create a Python class called EBook that inherits from the Book class.

Create a Python class called Animal with attributes name and color.

45. Problem to create an inheritance example in Python

In this Python oops program, we will create an inheritance example in Python, Python class called EBook that inherits from the Book class.

Inheritance example in Python

Steps to solve the program
  1. The Book class is defined with a constructor method __init__ that takes title, author, and pages as parameters and initializes the instance variables self.title, self.author, and self.pages with the provided values.
  2. The class also has three methods: get_title, get_author, and get_pages.
  3. The get_title method returns the title of the book.
  4. The get_author method returns the author of the book.
  5. The get_pages method returns the number of pages in the book.
  6. The EBook class is defined as a subclass of the Book class. It inherits the attributes and methods of the Book class.
  7. The __init__ method of the EBook class extends the functionality of the Book class’s __init__ method by adding two additional parameters: file_size and format. It initializes the instance variables self.file_size and self.format with the provided values.
  8. The open_book method prints a message indicating the opening of the e-book.
  9. The close_book method prints a message indicating the closing of the e-book.
  10. The code creates an object ebook of the EBook class by calling its constructor and passing the title “Harry Potter”, author “J.K. Rowling”, number of pages 300, file size “10MB”, and format “PDF” as arguments.
  11. The get_title, get_author, and get_pages methods inherited from the Book class are called on the ebook object to retrieve the respective book details, which are then printed.
  12. The file_size and format attributes specific to the EBook class are accessed directly from the ebook object and printed.
  13. The open_book method is called on the ebook object to simulate opening the e-book, and a corresponding message is printed.
  14. The close_book method is called on the ebook object to simulate closing the e-book, and a corresponding message is printed.
  15. Thus, we have created an inheritance example in Python.
				
					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()
				
			

Output:

				
					Title: Harry Potter
Author: J.K. Rowling
Pages: 300
File Size: 10MB
Format: PDF
Opening the e-book
Closing the e-book
				
			

Related Articles

Create a Python class called Book with attributes title, author, and pages.

Create a Python class called ShoppingCart with attributes items and total_cost.

44. Problem to create a Python class example

In this Python oops program, we will create a Python class example. Python class called Book with attributes title, author, and pages.

Python class example

Steps to solve the program
  1. The Book class is defined with a constructor method __init__ that takes title, author, and pages as parameters and initializes the instance variables self.title, self.author, and self.pages with the provided values.
  2. The class also has three methods: get_title, get_author, and get_pages.
  3. The get_title method returns the title of the book.
  4. The get_author method returns the author of the book.
  5. The get_pages method returns the number of pages in the book.
  6. The code creates an object book of the Book class by calling its constructor and passing the title “Harry Potter”, author “J.K. Rowling”, and number of pages 300 as arguments.
  7. The get_title method is called on the book object to retrieve the title of the book, which is then printed.
  8. The get_author method is called on the book object to retrieve the author of the book, which is then printed.
  9. The get_pages method is called on the book object to retrieve the number of pages in the book, which is then printed.
  10. Thus, we have created a Python class example.
				
					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())
				
			

Output:

				
					Title: Harry Potter
Author: J.K. Rowling
Pages: 300
				
			

Related Articles

Create a Python class called Laptop with attributes brand, model, and storage.

Create a Python class called EBook that inherits from the Book class.

43. Problem to create a Python class example

In this Python oops program, we will create a Python class example. Python class called Laptop with attributes brand, model, and storage.

Python class example

Steps to solve the program
  1. The Laptop class is defined with a constructor method __init__ that takes brand, model, and storage as parameters and initializes the instance variables self.brand, self.model, and self.storage with the provided values.
  2. The class also has three methods: start_up, shut_down, and check_storage_capacity.
    The start_up method simply prints a message indicating that the laptop is starting up.
  3. The shut_down method prints a message indicating that the laptop is shutting down.
  4. The check_storage_capacity method prints the storage capacity of the laptop in gigabytes.
  5. The code creates an object laptop of the Laptop class by calling its constructor and passing the brand “Dell”, model “XPS 13”, and storage capacity of 1000 as arguments.
  6. The start_up method is called on the laptop object to simulate starting up the laptop.
  7. The shut_down method is called on the laptop object to simulate shutting down the laptop.
  8. The check_storage_capacity method is called on the laptop object to display the storage capacity of the laptop.
  9. Thus, we have created a Python class example.
				
					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")
    
    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()
				
			

Output:

				
					Starting up the laptop
Shutting down the laptop
Storage capacity: 1000GB
				
			

Related Articles

Create a Python class called Phone with attributes brand, model, and storage. 

Create a Python class called Book with attributes title, author, and pages.