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):

    def __add__(self, T):
        R.__km = self.__km + T.__km

        return R


print("Enter first distance")

print("Enter second distance")


print("The sum of both distance is")


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 »

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.