Search code examples
pythonfunctioncountkeyerror

how can I change the function or avoid the error


I don't know if I wrote wrong the "line" function or if is something else in the final statement after "for", help me please. The program is about slope and compare between this values but first I need to find them, but something is not work. The code is the next:

import math

N = int(input("Number of points: "))

def line(x0,y0,x1,y1):
  if(x0==x1):
    print("\nThe slope doesn't exist\n")
    return None
  if((x0-x1)!=0):
    m = (y1-y0)/(x1-x0)
    return m

for i in range(N):
  for j in range(N):
    ind = None
    for ind in range(N):
      x_ind = {}
      y_ind = {}
      x_ind[i] = float(input("Enter x_" + str(ind) + ": "))
      y_ind[j] = float(input("Enter y_" + str(ind) + ": "))
    for _ in range(math.factorial(N-1)):
      line(x_ind[i], y_ind[j], x_ind[i+1], y_ind[j+1])
      

Solution

  • TL;DR - You are declaring your dictionaries inside for loop, so they are getting reset with every new iteration.


    I think you're trying to do this -

    N = int(input("Number of points: "))
    
    def line(x0,y0,x1,y1):
      # calculate slope for (x0,y0) and (x1,y1)
      if x0 == x1:            # it will be a vertical line, it has 'undefined' slope
        # print("The slope doesn't exist\n")
        return None           # Slope Undefined
      else:                   # this is implied, no need to put extra check --> x0-x1 != 0:
        return (y1-y0)/(x1-x0)
      pass
    
    # declare variables
    x_ind = {}
    y_ind = {}
    for i in range(N):
      # read inputs and update the existing variables
      x_ind[i] = float(input("Enter x_" + str(i) + ": "))
      y_ind[i] = float(input("Enter y_" + str(i) + ": "))
      print(x_ind, '\n', y_ind)
    
    # calculate slope for every pair of points
    for j in range(N):
      for k in range(j+1,N):
        m = line(x_ind[j], y_ind[j], x_ind[k], y_ind[k])
        print(f'slope of line made using points: ({x_ind[j]}, {y_ind[j]}) and ({x_ind[k]}, {y_ind[k]}) is {m}')
    

    Sample Input:

    Number of points: 3
    
    Enter x_0: 3
    Enter y_0: 0
    
    Enter x_1: 0
    Enter y_1: 4
    
    Enter x_2: 0
    Enter y_2: 0
    

    Sample Output:

    slope of line made using points: (3.0, 0.0) and (0.0, 4.0) is -1.3333333333333333
    slope of line made using points: (3.0, 0.0) and (0.0, 0.0) is -0.0
    slope of line made using points: (0.0, 4.0) and (0.0, 0.0) is None