Megan
Megan

Reputation: 205

Python Slope (given two points find the slope) -answer works & doesn't work;

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.

Upvotes: 10

Views: 45445

Answers (1)

coralvanda
coralvanda

Reputation: 6596

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)

Upvotes: 14

Related Questions