Why is my second variable (x2,y2) not defined while my first variable (x1,y1) is?

56 Views Asked by At
class Line():
    
    def __init__(self, coor1 , coor2):
        
        self.coor1 = coor1 
        self.coor2 = coor2 
      
    
    def distance(self):
        
        for x1,y1 in self.coor1, x2,y2 in self.coor2:
                
                distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
        
        return distance

coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)

li.distance()

Hi, I am not too sure why (x2,y2) wasn't able to be defined while the first variable (x1,y1) was. I am not too sure how to include both tuples in the for loop, but shouldn't both be defined or none of them are defined? Thanks!

1

There are 1 best solutions below

0
Martynas Žiemys On

You are not using the for loop correctly. You don't need a loop to assign multiple values at once. Just do:

class Line():
    
    def __init__(self, coor1 , coor2):
        self.coor1 = coor1 
        self.coor2 = coor2 
    
    def distance(self):
        x1,y1 = self.coor1 
        x2,y2 = self.coor2
        distance = ((x2-x1)**2 + (y2-y1)**2)**0.5
        return distance

    
coordinate1 = (3,2)
coordinate2 = (8,10)

li = Line(coordinate1,coordinate2)

print(li.distance())

Since the tuples contain two values, they will be assigned to the 2 variables separated by the comma:

x,y = (1,2)

is same as

x = 1
y = 2

Or you could just:

return sum([(i[0] - i[1])**2 for i in zip(self.coor1, self.coor2)])**0.5

And that would work with n-dimensional vectors.