Back to: Python Programming
Provided is some code to find the Distance between two points on a linear equation. Your task will be to tidy up this code, then add functionality to also find the Midpoint between the two points and the Gradient of the line passing through the two points.
# Import the math module to use the square root function.
import math
# Define the coordinates of the first point (p1) as a list.
p1 = [4, 0]
# Define the coordinates of the second point (p2) as a list.
p2 = [6, 6]
# Calculate the distance between the two points using the distance formula.
# The formula computes the Euclidean distance in a 2D space.
distance = math.sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))
# Print the calculated distance.
print(distance)
This code is pretty limiting, we need to amend it so that the user can add the two points. Here we will add them as a string, then split the sting into individual numbers in an array (list).
The split() method splits a string into a list, by default a <space> is the split point, but you can specify a different character. To split at commas use split(“,”).
# Import the math module to use the square root function.
import math
# Define the coordinates of the first point (p1) as a list.
coordinate1 = input("Enter first co-ordinate (x1,y1): ")
coordinate1 = coordinate1.replace(",", " ")
p1 = coordinate1.split() # <-- p1 now contains the split numbers, but as strings
p1 = [int(num) for num in p1] # <-- converts the string values to integers
# Define the coordinates of the second point (p2) as a list.
coordinate2 = input("Enter second co-ordinate (x2,y2): ")
p2 = coordinate2.split(",") # <-- Alternate way to split using a comma
p2 = [int(num) for num in p2]
# Calculate the distance between the two points using the distance formula.
# The formula computes the Euclidean distance in a 2D space.
print(f"The distance between {p1} and {p2} is: ")
distance = math.sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))
# Print the calculated distance.
print(round(distance,2))
Modify the code above to print the output on a single line.
Convert the code so that the calculation is done as a function called distance(…)

Add a second function to determine the gradient of a line between the two points

Finally, extend your code with a third function to calculate the midpoint between the points.
