Reputation: 53
I am new to programming and I have difficulties with solving a problem. I am coding it in python. May I have some help, please? So the condition says: A rectangular is set on 2 of its opposite angles (x1, x2) and (y1, y2). Find the area and the perimeter of the rectangular. The input is read from the console. The numbers x1, x2, y1, y2
are given one by one on a line.
Inputs and Outputs:
An example:
my code:
x1 = float(raw_input("x1 = "))
y1 = float(raw_input("y1 = "))
x2 = float(raw_input("x2 = "))
y2 = float(raw_input("y2 = "))
if x1 > x2 and y1 < y2:
a = x1 - x2
b = y2 - y1
else:
a = x2 - x1
b = y1 - y1
area = a * b
perimeter = 2 * (a + b)
print area
print perimeter
Upvotes: 1
Views: 2880
Reputation: 717
You are on the right track!
Let me make a few suggestions:
There is nothing wrong with this. (Unless you want to use Python3, where where raw_input
is now just input
)
x1 = float(raw_input("x1 = "))
y1 = float(raw_input("y1 = "))
x2 = float(raw_input("x2 = "))
y2 = float(raw_input("y2 = "))
If you use the builtin function abs()
, you do not have to worry about the sign of (x1 - x2)
and (y1 - y2)
! Where abs(x)
gives the absolute value of x
.
width = abs(x1 - x2)
height = abs(y1 - y2)
Now that we have the height and width, we can use you code to calculate the area and perimeter:
area = height * width
perimeter = 2 * (height + width)
Check if your rectangle is a square:
if height == width:
print "It's a square!"
x1 = float(raw_input("x1 = "))
y1 = float(raw_input("y1 = "))
x2 = float(raw_input("x2 = "))
y2 = float(raw_input("y2 = "))
width = abs(x1 - x2)
height = abs(y1 - y2)
area = height * width
perimeter = 2 * (height + width)
print area
print perimeter
if height == width:
print "It's a square!"
Let me know if you need me to explain anything!
Upvotes: 1