How to calculate the distance between two points using return methods in python?

42,964

Solution 1

Why don't you use math.hypot() to calculate the distance?

>>> import math
>>> p1 = (3, 5)  # point 1 coordinate
>>> p2 = (5, 7)  # point 2 coordinate
>>> math.hypot(p2[0] - p1[0], p2[1] - p1[1]) # Linear distance 
2.8284271247461903

Solution 2

Store the result in a variable

import math

def calculateDistance(x1,y1,x2,y2):
     dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
     return dist

distance = calculateDistance(2,4,6,8)

print distance

Or print the result directly

import math

def calculateDistance(x1,y1,x2,y2):
     dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
     return dist

print calculateDistance(2,4,6,8)
Share:
42,964
Admin
Author by

Admin

Updated on May 13, 2021

Comments

  • Admin
    Admin almost 3 years

    I'm still new to python and have been trying to get the hang of it. I've been trying to learn simple return methods but I can't seem to get the hang of it. I have been trying to find the distance between two points and this is what I have so far. If anyone could help me figure this out it would be very helpful! Thank you!

    import math
    
    def calculateDistance(x1,y1,x2,y2):
         dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
         return dist
    
    calculateDistance(2,4,6,8)
    
    print calculateDistance
    
  • piit79
    piit79 almost 3 years
    While this works, the answer doesn't address the issue in the question - the fact that the user wasn't correctly printing the return value of the function. Furthermore, the user specifically mentioned coding a function that returns a value, while your prints it instead.