0

I am having difficulty with this piece of code I am writing that should output both the slope and distance between two points.

Looking at it in the python visualizer, it seems to be able to calculate the values, however, the distance variable does not get it's value saved. It is overwritten by the value of the slope.

I am having trouble understanding how I should be using return in the function definition, as that seems to be the issue.

def equation(x,y,x1,y1):
  distance=math.sqrt(((x-x1)**2)+((y-y1)**2))
  if x!=x1 and y1!=y:
    slope=(y1-y)/(x1-x)
    return slope
  else:
    slope='null'
    return slope
  return distance
slope=equation(1,3,2,1)
print(slope)
distance=equation(1,3,2,1)
print(distance)

The output of the code here is the same for both variables.

3
  • The return statement of distance will never reach. because both path of the if-else returns and the code never gets a chance to reach distance. May be you wanted to return a tuple instead of a scalar?
    – mshsayem
    Jan 23, 2020 at 5:03
  • here distance never returns , since in your if and else your and "if doesnt match everytime " it goes to else so every time slope null values will be returned so you can use two diffrent equation one for slope and one for distance or you can return the tuple Jan 23, 2020 at 5:07
  • @PWier check the solution Jan 23, 2020 at 5:15

2 Answers 2

0

If you want both to be different function calls i.e. slope=equation(1,3,2,1) and distance=equation(1,3,2,1), then try the first approach and if you want both to be called in single line i.e. slope, distance=equation(1,3,2,1) then try second approach:

First Approach

import math
def equation(x,y,x1,y1,var):
  if var == "slope":
    if x!=x1 and y1!=y:
      slope=(y1-y)/(x1-x)
      return slope
    else:
      slope='null'
      return slope
  elif var == "distance":
    distance=math.sqrt(((x-x1)**2)+((y-y1)**2))
    return distance
slope=equation(1,3,2,1,"slope")
print(slope)
distance=equation(1,3,2,1,"distance")
print(distance)

Second Approach

def equation(x,y,x1,y1):
  distance=math.sqrt(((x-x1)**2)+((y-y1)**2))
  if x!=x1 and y1!=y:
    slope=(y1-y)/(x1-x)
    return slope,distance
  else:
    slope='null'
    return slope,distance
slope, distance=equation(1,3,2,1)
print(distance)
print(slope)
1
  • Thanks, this was most helpful. I appreciate the two approaches you've listed, helps me understand the code better.
    – PWier
    Jan 23, 2020 at 5:16
-1

Return statement exits from function when it comes across on it. Return a tuple from function.

def equation(x,y,x1,y1):
    # calculate slope and distance
    return slope, distance

slope,distance = equation(1,3,2,1)
print(slope)
print(distance)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.