Home »
Python »
Python programs
Python program to add two distances
Here, we are going to write a Python program to add two distances using class and object concepts.
Submitted by Shivang Yadav, on February 13, 2021
Problem Statement: 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
We can additionally use classes to make the program better.
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.
Python class & object programs »