Define a class train with following members…Using python.

In Python programming we have many functions and libraries included. but when we talk about user defined function then which in defined by user and can be call again and again withing the same program. This is a good practice done by programmers. “class” is also a part of user defined function. class help us to build data and their functionality together. New type of object is created when we create new class. Each class instance have attributes attached with it which help you to maintain its state. We will discuss a example: Define A Class Train With Following Members to understand the syntax and use of class.

Example 1.

Q. Define a class train with following members. (TrainNo ,Destination ,Distance ,Fuel)

  • A member function calfuel() to calculate and assign value of fuel as per the following criteria:
  • feedinfo(): to input train no, destination, distance and invoke calfuel() function to assign value of fuel.
  • showinfo(): to display all the details for a train.
values

Solution

#Python 3
class train:

    def train_(self, TrainNo ,Destination ,Distance ,fuel):
        self.TrainNo = 0
        self.Destination = Destination
        self.Distance = 0
        self.fuel = 0

#define calfuel which check the condition of fuel as per distance.
    def calfuel(self):
        distance = self.Distance
        if distance <= 1500 : 
            self.fuel = 250
            print(f"Fuel required to travel {distance} is upto ",self.fuel)
        elif distance > 1500 and distance <=3000:
            self.fuel = 1000
            print(f"Fuel required to travel {distance} is upto ",self.fuel)
        else:
            self.fuel = 2500
            print(f"Fuel required to travel {distance} is upto ",self.fuel) 

#define feedinfo which takes the value from user                      

    def feedinfo(self):
        self.TrainNo = int(input("Enter the train number : "))
        self.Destination = str(input("Enter the Destination : "))
        self.Distance = int(input("Enter the distance that you need to travel"))
        s.calfuel() 

#define showinfo which shows all the user value and calculate the fuel and desplay      

    def showinfo(self):        
      print("\n***Train details***")   
  
        print("\n__________________________________________________________")  
        print("Train Number : ", self.TrainNo)  
        print("Destination : ",self.Destination)  
        print("Distance to travel ", (self.Distance))
        print("Fuel required upto (LITERS) ", self.fuel)  
        print("__________________________________________________________")   

#calling all the user defined functions              

s = train()
TrainNo = 0
Destination = 0
Distance = 0
fuel = 0
s.train_(TrainNo ,Destination ,Distance ,fuel)
s.feedinfo()
s.showinfo() 

Output 

Enter the train number : 34562 
Enter the Destination : Ahmedabad
Enter the distance that you need to travel : 1000
Fuel required to travel 1000 is upto  250
***Train details****  
_________________________________________________________
Train Number :  34562
Destination :  Ahmedabad
Distance to travel  1000
Fuel required upto (LITERS)  250
__________________________________________________________ 

  

It has three different case as mention in question above accordingly you can check all the cases in output.

More solved examples on python class.

Q. Define a class employee with the following specifications:                                              

  •   empno integer
  •   ename 20 characters
  •   basic, hra, da float
  •   netpay float
  •       calculate() A function to calculate basic + hra + da with float return type

o   havedata() function to accept values for empno, sname, basic, hra, da and invoke calculate() to calculate netpay.

o   dispdata() function to display all the data members on the screen.

Related article : Why To Learn Python Scope, Applications, Salary, Courses.

class employee:  

       def employee_(self, empNO, Name, basic):      
           self.empNO = empNO #user
           self.Name = Name  #user
            self.basic  = basic #user

       def ctotal(self):
           HRA = (self.basic/100)*30
           DA = (self.basic/100)*25
            print("\nNetpay =", (self.basic + HRA + DA))
         
       def read_data(self):
           self.empNO = int(input("\nEmployee Number:")) 
           self.Name = str(input("Employee Name :")) 
            self.basic = int(input("\nYour Basic in Rupee. :"))

       def display_data(self):  
               print("\n**Your details**")  
               print("\n____________________")  
               print("Employee Number : ", self.empNO)  
               print("Employee Name : ", self.Name)  
               print("Basic is Rs.", (self.basic))
               print("House rent allowance (HRA) 30% : ", (self.basic/100)*30)  
               print("Dearness Allowance (DA) 25% : ", (self.basic/100)*25)  
               s.ctotal() 
                print("____________________")  
             
s = employee()
empNO = 0
Name = 0 
basic = 0
s.employee_(empNO, Name, basic)
s.read_data()
s.ctotal()
s.display_data()

Employee Number : 12341234
Employee Name : Snahal Kumar
Your Basic in Rupee. : 100
Netpay = 155.0

**Your details**
____________________
Employee Number :  12341234
Employee Name :  Snahal Kumar
Basic is Rs. 100
House rent allowance (HRA) 30% :  30.0
Dearness Allowance (DA) 25% :  25.0 

Netpay = 155.0
____________________

Q. Define a class HOTEL with the following description:

Ø  Rno             //Data Member to store Room No

Ø  Name          //Data Member to store customer Name

Ø  Tariff           //Data Member to store per day charge

Ø  NOD           //Data Member to store Number of days

Ø  CALC         //A function to calculate and return amount as NOD*Tariff and if the value of NOD*Tariff is more than 10000 then as 1.05*NOD*Tariff

o   Checkin( )   //A function to enter the content RNo,Name, Tariff and NOD

o   Checkout()  //A function to display Rno, Name, Tariff, NOD and Amount (Amount to be displayed by calling function CALC( 

#Python
class hotel: 


   def hotel_(self, Rno, Name, Tariff, NOD, x, y): 
       self.Rno = 0 
       self.Name = Name 
       self.Tariff = 0 
       self.NOD = 0 
       self.x = NOD*Tariff 
        self.y = 0 

   def CALC(self): 
       self.x = (self.NOD)*(self.Tariff) 
       if self.x < 10000: 
           print("RETURNED = Rs.",self.x) 
       else: 
           self.y = (self.x)*1.05 
            print("RETURNED = Rs. ",self.y) 
         
   def Checkin(self): 
       self.Rno=int(input("Room number:")) 
       self.Name=str(input("Name of the person:")) 
       self.Tariff=float(input("Per day charge:")) 
        self.NOD=int(input("eneter the number of number of days:")) 

   def Checkout(self): 
       print("room num",self.Rno)  
       print("name:",self.Name) 
       print("tariff:",self.Tariff) 
       print("Total number  of days:",self.NOD) 
        s.CALC() 

s=hotel()
Rno=0
Name=0
Tariff=0
NOD=0
x=0
y=0

s.hotel_(Rno,Name,Tariff,NOD,x,y)  
s.Checkin() 
s.CALC()
s.Checkout()

Room number: 3
Name of the person: Snahal Kumar
Per day charge: 2000
eneter the number of number of days: 11
RETURNED = Rs.  23100.0
room num 3

name: Snahal Kumar
tariff: 2000.0
Total number  of days: 11
RETURNED = Rs.  23100.0

Q. Define a class Applicant with following description:

  • ANo : ( Admission Number): type long
  • Name : type string
  • Agg :(Aggregate Marks) : type float
  • Grade :type str
  • A member function GradeMe( ) to find the Grade as per the Aggregate Marks obtained by a student. Equivalent Aggregate marks range and the respective Grades are shown as follows
  1. Aggregate Marks           Grade
  2. = 80        A
  3. Less than 80 and > = 65  B
  4. Less than 65 and > = 50  C
  5. Less than 50          D

o   A function Enter( ) to allow user to enter values for ANo, Name, Agg & call function GradeMe( ) to find the Grade

o   A function Result ( )   to allow user to view the content of all the data members.

Related Article : Top 5 Programming Languages In World To Boost Your Carrier.

class applicant: 

   def applicant_(self,ANo,Name,Agg,Grade): 
       self.ANo=0 
       self.Name=Name 
       self.Agg=0.0 
        self.Grade=Grade 

   def GradeMe(self):
       Agg=self.Agg 
       if Agg>=80: 
           self.Grade='A'  
           print("\n marks>80 ",self.Grade) 

       elif Agg<80 and Agg>=65: 
           self.Grade='B'  
            print("\n Less then 80 ",self.Grade) 

       elif Agg<65 and Agg>=50: 
           self.Grade='C'       
            print("\n Between 65 - 50 ",self.Grade) 

       else: 
           self.Grade='D'  
            print("\n marks less than 50 is ",self.Grade) 

   def Enter(self): 
       self.ANo=int(input("Enter the Admission Number:")) 
       self.Name=str(input("Enter the Name of the Applicant:"))   
       self.Agg=float(input("Enter the Aggregate marks:")) 
        s.GradeMe() 

   def Result(self): 
       print("\n______________________") 
       print("Admission Number:",self.ANo)  
       print("Name:",self.Name) 
       print("Aggregate Marks:",self.Agg)   
       print("grade:",self.Grade)     
        print("_______________") 

s=applicant()
ANo=0
Name=0
Agg=0
Grade=0 

s.applicant_(ANo,Name,Agg,Grade)
s.Enter()
s.Result()

Enter the Admission Number: 3588
Enter the Name of the Applicant: Snahal Kumar
Enter the Aggregate marks: 50
Between 65 - 50  C


______________________
Admission Number: 3588
Name: Snahal Kumar
Aggregate Marks: 50.0
grade: C
_______________

Q. Define a class Student with the following specifications :                                                

  •   roll_no        integer
  •   name           str
  •   class            str
  •   marks[5]      integer
  •   percentage   float
  •       Calculate() a function that calculates overall percentage of marks and return the percentage of marks.

o   Readmarks() a function that reads marks and invoke the Calculate function.

o   Displaymarks() a function that prints the marks.

Know more : All About Electronics And Communication Engineering

class Student:
  
       def Student_(self, roll_no, name, Class, TMarks, percentage,S1,S2,S3,S4,S5):
           self.roll_no=0
           self.name=name
           self.Class=0
           self.TMarks=0
           self.percentage=0
           self.S1=0
           self.S2=0
           self.S3=0
           self.S4=0
            self.S5=0
  
        def calculate(self):
     
           #Calculate total, average and percentage one by one
           self.TMarks = self.S1 + self.S2 + self.S3 + self.S4 + self.S5
           print("total marks",self.TMarks)
           self.percentage =(self.TMarks/500.0)*100
            print(f"Overall percentage {self.percentage}%")

        def Readmarks(self):

           print("Enter marks of five subjects:")
           self.S1=float(input("Marks in maths out of 100 :" ))
           self.S2=float(input("Marks in english out of 100 :"))
           self.S3=float(input("Marks in Python out of 100 :"))
           self.S4=float(input("Marks in physics out of 100 :"))
            self.S5=float(input("Marks in chemistry out of 100 :"))

       def Displaymarks(self):
           print("\n***********************************")
           print("Marks out of 100")
           print("Maths      ", self.S1)
           print("english    ", self.S2)
           print("Python     ", self.S3)
           print("physics    ", self.S4)
           print("chemistry  ", self.S5)
           s.calculate()
            print("***********************************")

s=Student()
roll_no=0
name=0
Class=0
TMarks=0
percentage=0
S1=0
S2=0
S3=0
S4=0
S5=0

s.Student_(roll_no,name,Class,TMarks,percentage,S1,S2,S3,S4,S5)
s.Readmarks()
s.Displaymarks()

Enter marks of five subjects:
Marks in maths out of 100 : 80
Marks in english out of 100 : 84
Marks in Python out of 100 : 91
Marks in physics out of 100 : 95
Marks in chemistry out of 100 : 78

***********************************
Marks out of 100
Maths       80.0
english     84.0
Python      91.0
physics     95.0
chemistry   78.0
total marks 428.0

Overall percentage 85.6%
***********************************

This is the solution of some basic problems on class using python, You can change the design of the output and words as per your choice. I have provided a basic syntax on this problems. 

“Also see  some examples based on Array in Python below.”

Q3 Write a function that will accept a 2-D array and its row and column size as argument and find sum of rows and columns.
Click here for answer.

Q4. Write a function in python to find the sum of both left and right diagonal elements from a two dimensional array (matrix).
Click here for answer.

Leave a Comment

Your email address will not be published. Required fields are marked *