Q:

Python program to add two distances

belongs to collection: Python class & object programs

0

 Python program to add two distances entered by the user.

Problem Description: We need to find the sum of distances that are provided by the user as input in km, m and cm format.

Steps to find the sum of distances:

  • Step 1: Take both the distances in cm, m and km format.
  • Step 2: Add both the distances, adding cm, m and km. Also, use adequate conversion.
    1 m = 100 cm
    1 km = 1000 m

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to add two distances using class

class Distance:
    def GetDistance(self):
        self.__cm=int(input("Enter CM: "))
        self.__m=int(input("Enter M: "))
        self.__km = int(input("Enter KM: "))

    def PutDistance(self):
        print(self.__km,self.__m,self.__cm)

    def __add__(self, T):
        R=Distance()
        R.__cm=self.__cm+T.__cm
        R.__m=self.__m+T.__m
        R.__km = self.__km + T.__km
        R.__m=R.__m+(R.__cm//100)
        R.__cm=R.__cm%100
        R.__km=R.__km+(R.__m//1000)
        R.__m=R.__m%1000

        return R

D1=Distance()
D2=Distance()

print("Enter first distance")
D1.GetDistance()

print("Enter second distance")
D2.GetDistance()

D3=D1+D2

print("The sum of both distance is")
D3.PutDistance()

Output:

Enter first distance
Enter CM: 45
Enter M: 43
Enter KM: 21
Enter second distance
Enter CM: 34
Enter M: 21
Enter KM: 54
The sum of both distance is 
75 64 79

In the above code, we have created a class Distance that defines methods that perform basic operations like reading input from the user, adding the distances and printing output. Then we have created the objects of the class to get two inputs and then another object to store the sum of distances.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python class & object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to add accounts in a bank (Bank Man... >>
<< Program to build flashcard using class in Python...