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.