3D Coordinates - Python Programming Exercise

In this exercise, you will develop a Python class "Point3D" that will represent a point in three-dimensional space with coordinates X, Y, and Z. This exercise is perfect for practicing class definition, method implementation, and object-oriented programming in Python. By implementing this class, you will gain hands-on experience in handling class definitions, method implementation, and object-oriented programming in Python. This exercise not only reinforces your understanding of object-oriented programming but also helps you develop efficient coding practices for managing user interactions.

 Category

Mastering Python Classes in OOP

 Exercise

3D Coordinates

 Objective

Develop a Python class "Point3D" that will represent a point in three-dimensional space with coordinates X, Y, and Z. The class should have the following methods:

- MoveTo, which allows updating the point's coordinates.

- DistanceTo(Point3D p2), a method that calculates the distance between the current point and another given point.

- ToString, which returns a string representation of the point, such as "(2,-7,0)".

- Additionally, provide getters and setters for the coordinates.

The main program should create an array of 5 Point3D objects, collect input data for them, and then compute and display the distances from the first point to each of the others.

 Example Python Exercise

 Copy Python Code
import math

class Point3D:
    def __init__(self, x=0, y=0, z=0):
        """
        Initializes a Point3D object with coordinates (x, y, z).

        Parameters:
            x (float): The x-coordinate of the point.
            y (float): The y-coordinate of the point.
            z (float): The z-coordinate of the point.
        """
        self.x = x
        self.y = y
        self.z = z

    # Getter for x-coordinate
    def get_x(self):
        return self.x

    # Setter for x-coordinate
    def set_x(self, x):
        self.x = x

    # Getter for y-coordinate
    def get_y(self):
        return self.y

    # Setter for y-coordinate
    def set_y(self, y):
        self.y = y

    # Getter for z-coordinate
    def get_z(self):
        return self.z

    # Setter for z-coordinate
    def set_z(self, z):
        self.z = z

    def move_to(self, x, y, z):
        """
        Updates the coordinates of the point to the new values.

        Parameters:
            x (float): The new x-coordinate.
            y (float): The new y-coordinate.
            z (float): The new z-coordinate.
        """
        self.x = x
        self.y = y
        self.z = z

    def distance_to(self, p2):
        """
        Calculates the distance between the current point and another Point3D.

        Parameters:
            p2 (Point3D): The second point to calculate the distance to.

        Returns:
            float: The distance between the two points.
        """
        return math.sqrt((self.x - p2.get_x()) ** 2 + (self.y - p2.get_y()) ** 2 + (self.z - p2.get_z()) ** 2)

    def to_string(self):
        """
        Returns a string representation of the point in the format (x, y, z).

        Returns:
            str: The string representation of the point.
        """
        return f"({self.x}, {self.y}, {self.z})"


# Main program to test the Point3D class
def main():
    # Create an empty list to hold 5 Point3D objects
    points = []

    # Collect input data for 5 points and create Point3D objects
    for i in range(5):
        print(f"Enter coordinates for Point {i+1}:")
        x = float(input("Enter x-coordinate: "))
        y = float(input("Enter y-coordinate: "))
        z = float(input("Enter z-coordinate: "))
        point = Point3D(x, y, z)
        points.append(point)

    # Compute and display the distances from the first point to each of the others
    print("\nDistances from Point 1 to other points:")
    for i in range(1, 5):
        distance = points[0].distance_to(points[i])
        print(f"Distance from Point 1 to Point {i+1}: {distance:.2f}")

    # Display the string representation of all points
    print("\nPoints:")
    for i, point in enumerate(points):
        print(f"Point {i+1}: {point.to_string()}")


# Run the main program
if __name__ == "__main__":
    main()

 Output

Enter coordinates for Point 1:
Enter x-coordinate: 1
Enter y-coordinate: 2
Enter z-coordinate: 3

Enter coordinates for Point 2:
Enter x-coordinate: 4
Enter y-coordinate: 5
Enter z-coordinate: 6

Enter coordinates for Point 3:
Enter x-coordinate: 7
Enter y-coordinate: 8
Enter z-coordinate: 9

Enter coordinates for Point 4:
Enter x-coordinate: 10
Enter y-coordinate: 11
Enter z-coordinate: 12

Enter coordinates for Point 5:
Enter x-coordinate: 13
Enter y-coordinate: 14
Enter z-coordinate: 15

Distances from Point 1 to other points:
Distance from Point 1 to Point 2: 5.20
Distance from Point 1 to Point 3: 10.39
Distance from Point 1 to Point 4: 15.56
Distance from Point 1 to Point 5: 20.79

Points:
Point 1: (1.0, 2.0, 3.0)
Point 2: (4.0, 5.0, 6.0)
Point 3: (7.0, 8.0, 9.0)
Point 4: (10.0, 11.0, 12.0)
Point 5: (13.0, 14.0, 15.0)

 Share this Python Exercise

 More Python Programming Exercises of Mastering Python Classes in OOP

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Catalog & Navigation

    In this exercise, you will develop a Python program to enhance the Catalog application, where the "Main" function displays a menu that allows users to input new data ...

  •  Object array: tables

    In this exercise, you will develop a Python class called "Table". The class should include a constructor to initialize the width and height of the table. It should al...

  •  House

    In this exercise, you will develop a Python program with the following classes: House: Create a class called "House" with an attribute for "area". Include a construc...

  •  Array of Tables and Coffee Tables

    In this exercise, you will develop a Python project called "Tables2," extending the "Tables" project. In this project, define a class called "CoffeeTable" that inheri...

  •  Encryptor & Decryptor

    In this exercise, you will develop a Python class called "Encryptor" for text encryption and decryption. This exercise is perfect for practicing class definiti...

  •  Advanced Number Systems

    In this exercise, you will develop a Python program to represent complex numbers, which consist of a real part and an imaginary part. This exercise is perfect ...