Create StudentRecord with name, age and grades, with methods for the average and a summary.
Output
Meena, 16, average 86.33
Approach
sum(grades) / len(grades).
Solution
Python
classStudentRecord:def__init__(self,name,age,grades):self.name,self.age,self.grades=name,age,gradesdefaverage(self):returnround(sum(self.grades)/len(self.grades),2)defshow(self):print(f"{self.name}, {self.age}, average {self.average()}")StudentRecord("Meena",16,[88,92,79]).show()
Output
Meena, 16, average 86.33
Learn the concept
New to this topic? Read the lesson, then come back.
Create ElectricCar (inherits Car) with battery_size and range_per_charge and a method to calculate the range.
Output
Tata Nexon EV 300.0 km
Approach
Range here is battery size (kWh) times km per kWh.
Solution
Python
classCar:def__init__(self,make,model,year):self.make,self.model,self.year=make,model,yearclassElectricCar(Car):def__init__(self,make,model,year,battery_size,range_per_charge):super().__init__(make,model,year)self.battery_size=battery_size# kWhself.range_per_charge=range_per_charge# km per kWhdeftotal_range(self):returnself.battery_size*self.range_per_chargeev=ElectricCar("Tata","Nexon EV",2025,40,7.5)print(ev.make,ev.model,ev.total_range(),"km")
Output
Tata Nexon EV 300.0 km
Learn the concept
New to this topic? Read the lesson, then come back.
Create a BankAccount class with account_number and balance, and methods to deposit and withdraw.
Output
AC-1001 1200
Error: insufficient funds
Approach
Validate amounts in each method.
Solution
Python
classBankAccount:def__init__(self,account_number,balance=0):self.account_number=account_numberself.balance=balancedefdeposit(self,amount):ifamount<=0:raiseValueError("deposit must be positive")self.balance+=amountdefwithdraw(self,amount):ifamount>self.balance:raiseValueError("insufficient funds")self.balance-=amountacc=BankAccount("AC-1001",1000)acc.deposit(500)acc.withdraw(300)print(acc.account_number,acc.balance)try:acc.withdraw(5000)exceptValueErrorase:print("Error:",e)
Output
AC-1001 1200
Error: insufficient funds
Learn the concept
New to this topic? Read the lesson, then come back.