Reputation: 29
I am writing a program that prompts a user to input two opposite corners of a rectangle: (x1, y1) and (x2, y2). It is assuming the sides of the rectangle are parallel to the x and y axes. If the user's (x1, y1) and (x2, y2) coordinates fail to create a rectangle, then it will print the following statement:
You have entered two points that fail to create a rectangle. Exiting the program.
Should the user enter the appropriate coordinates to create a rectangle, the program then prompts the user to enter the third point's coordinates (x, y).
The program prints true or false based on whether the point (x, y) is inside the rectangle. If the point lies on or outside the rectangle, the program should print false.
Enter x1: 1
Enter y1: 1
Enter x2: 1
Enter y2: 5
You have entered two points that fail to create a rectangle. Exiting the program.
Enter x1: 0
Enter y1: 0
Enter x2: 3.5
Enter y2: 3.5
Enter x: 1.3
Enter y: 3.5
False
Enter x1: 4
Enter y1: 4
Enter x2: 0
Enter y2: 0
Enter x: 2
Enter y: 2
True
# Prompt the user to input (x1, y1), (x2, y2), and (x, y)
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))
# If (x1, y1) and (x2, y2) do not form a rectangle, print the following statement and exit the program
if (x1 == x2 and y1 < y2):
print("You have entered two points that failed to create a rectangle. Exiting the program")
# Else, prompt the user to enter the (x, y) coordinates
else:
x = float(input("Enter x: "))
y = float(input("Enter y: "))
# Print if the (x, y) coordinates are inside the rectangle (true), or on or outside it (false)
result = (x > x1 and x < x2 and y > y1 and y < y2)
print(result)
While the program works, it is not correct and consistent with the (x1, y1), (x2, y2), and (x, y) coordinates that I enter. For instance, if I enter the following coordinates below, I receive false instead of true. The issue is the (x, y) coordinate do lie inside the rectangle.
I believe my code's logic is not correct, particularly with the result variable. I have looked through various solutions online on different if-else statements and logic; however, I cannot figure it out. I have tried messing with the logic by flipping the signs to no avail.
I am open to feedback on what I am missing and how I can improve my code. Thank you.
Enter x1: 4
Enter y1: 4
Enter x2: 0
Enter y2: 0
Enter x: 2
Enter y: 2
**False**
Upvotes: 0
Views: 1216
Reputation: 2721
You can do this:
result = (((x2 > x > x1) or (x1 > x > x2)) and ((y2 > y > y1) or (y1 > y > y2)))
Also for the if else part, change it to:
if (x1 == x2 or y1 == y2):
print("You have entered two points that failed to create a rectangle. Exiting the program")
Upvotes: 1