Trying to figure out the function to return the slope of a line in Python. Problem directions are to find the slope of m with the slope coordinates given. Read through several other stack overflow posts, but none seem to make a working solution. Here are a variety of the variations I've tried:
def slope(x1, y1, x2, y2):
m = 0
b = (x2 - x1)
d = (y2 - y1)
if b != 0:
m = (d)/(b)
return m
slope(2, 3, 6, 7)
def slope(x1, y1, x2, y2):
m = 0
a = float(x1)
b = float(x2)
c = float(y1)
d = float(y2)
m = (d-c)/(b-a)
return m
slope(2, 3, 6, 7)
def slope(x1, y1, x2, y2):
m = ''
a = float(x1)
b = float(x2)
c = float(y1)
d = float(y2)
m = (d-c)/(b-a)
return m
slope(2, 3, 6, 7)
def slope(x1, y1, x2, y2):
m = 0
b = (x2 - x1)
d = (y2 - y1)
if b == 0:
m = None
else:
m = (d)/(b)
return m
slope(2, 3, 6, 7)
def slope(x1, y1, x2, y2):
m = (y2-y1)/(x2-x1)
return m
slope(2, 3, 6, 7)
At one point, I received error messages regarding a global m. I also tried making a " m = 0 " outside the function, but that didn't help. Also received "AssertionError: 0 != 1"
I've gotten the right answer followed by a second line =>None and when submitting the system says that it is not correct.
You can find the line's slope using the linregress() function if we define the x and y coordinates as arrays. The following code uses the linregress() method of the SciPy module to calculate the slope of a given line in Python.
Use the slope formula to find the slope of a line given the coordinates of two points on the line. The slope formula is m=(y2-y1)/(x2-x1), or the change in the y values over the change in the x values. The coordinates of the first point represent x1 and y1.
Your math is spot on, so that's not the problem. I tested all of your functions by adding print
statements, and they all correctly returned 1.0
.
Does your system require that you print out the returned value? Do this.
def slope(x1, y1, x2, y2):
m = (y2-y1)/(x2-x1)
return m
print slope(2, 3, 6, 7)
You can even optimize a bit more by leaving out the variable and directly returning your calculation, like this:
def slope(x1, y1, x2, y2):
return (y2-y1)/(x2-x1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With