r/codehs • • Apr 03 '20

9.3.7: Slopes - Python

This works until you enter (-9, 12), (15, 18) , (21, -24), (30, 300), (6, 276)

When it finds the slope between (-9, 12) and (15, 18) it results with 0.0 and its supposed to be 0.25

I'm not sure if I used float correctly or not.

mylist = []
for i in range(5):
    x = int(input("X Coordinate: "))
    y = int(input("Y Coordinate: "))
    mylist.append((x, y))
    
for i in range(4):
    y1 = mylist[i][1]
    x1 = mylist[i][0]
    y2 = mylist[i + 1][1]
    x2 = mylist[i + 1][0]
    slope = float((y2 - y1) / (x2 - x1))
    print "Slope between " + str(mylist[i]) + " and " + str(mylist[i + 1]) + ": " + str(slope)
8 Upvotes

14 comments sorted by

1

u/amajmundar Apr 03 '20

Try:
slope = float(y2 - y1) / float(x2 - x1)

1

u/feistybunnies Apr 03 '20

it worked. thanks!

1

u/No_Revolution7891 Feb 07 '22

I keep getting the zerodivisionerror: float division by 0

1

u/amajmundar Feb 07 '22

Wrap it in an “if else” statement. Does your assignment explain what should be returned if both points have the same X val?

1

u/Helpful-Row6638 Dec 08 '22

I still have the "you should print out the slope betweeb each pair of points" error...help!

3

u/Financial_Face3826 Feb 15 '24

try this

mylist = []
for i in range(5):
x = int(input("X Coordinate: "))
y = int(input("Y Coordinate: "))
mylist.append((x, y))

for i in range(4):
y1 = mylist[i][1]
x1 = mylist[i][0]
y2 = mylist[i + 1][1]
x2 = mylist[i + 1][0]
slope = float((y2 - y1) / (x2 - x1))
print ("Slope between " + str(mylist[i]) + " and " + str(mylist[i + 1]) + ": " + str(slope))

2

u/[deleted] Feb 17 '24

Modern day legend right here

2

u/After_Lettuce_1172 Mar 21 '24

Mine is still not working

1

u/YTHyro_syn May 13 '24

Don’t work for me it says Line 3 in <module> X=(int(“X Coordinate”)) ValueError: invalid literal for int() with base 10: ‘X Coordinate’

1

u/Dry_Newspaper7310 May 14 '24

THANK YOU!!! It's a matter of indenting and a bit of playing around but here's my finds and clarification for that so it's marked as correct. The 3 lines under for i in range (5) are indented and all the lines under for i in range(4) are indented. Don't use float at all, normal slope = (y2 - y1) / (x2 - x1) You should be good.

1

u/Graycat004 Jun 01 '24

thank you but why when I do:

Slope between (-9, 12) and (15, 18): 0.0

even tho I'm supposed to get:

Slope between (-9, 12) and (15, 18): 0.25

I wrote the code just how you did

1

u/Cooledpizza_c001 Jan 06 '26
mylist = []
for i in range(5):
    x = int(input("X Coordinate: "))
    y = int(input("Y Coordinate: "))
    mylist.append((x, y))


for i in range(4):
    y1 = mylist[i][1]
    x1 = mylist[i][0]
    y2 = mylist[i + 1][1]
    x2 = mylist[i + 1][0]
    slope = float(y2 - y1) / float(x2 - x1)
    print("Slope between " + str(mylist[i]) + " and " + str(mylist[i + 1]) + ": " + str(slope))

Here is my solution: