Calculates the width of a rectangle given the area and perimeter - python

Ive based the e1 and e2 sections of code as two halves of the google equation found when asking calculate width of a rectangle given perimeter and area.
This section of code is set to be part of a larger piece that displays the calculated rectangle in a visual form instead of using integers, however when i test it, the answer it gives is incorrect.
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
e1 = int((perim / 4) + .25)
e2 = int(perim**2 - (16 * area))
e3 = int(math.sqrt(e2))
width = int(e1 * e3)
print(width)

It's recommended you name your variables better so we know what you're trying to calculate.
From the Google formula, you should just translate it directly.
import math
def get_width(P, A):
_sqrt = math.sqrt(P**2 - 16*A)
width_plus = 0.25*(P + _sqrt)
width_minus = 0.25*(P - _sqrt)
return width_minus, width_plus
print(get_width(16, 12)) # (2.0, 6.0)
print(get_width(100, 40)) # (0.8132267551043526, 49.18677324489565)
You get zero because int(0.8132267551043526) == 0
Important note: Your calcuation doesn't check
area <= (perim**2)/16

Here is the fixed code :
import math
print("Welcome to Rectangles! Please dont use decimals!")
S = int(input("Area "))
P = int(input("Perim "))
b = (math.sqrt (P**2-16*S)+P) /4
a = P/2-b
print (a,b)

If you don't need to use this equation specifically, it'd be easier to just brute force it.
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
lengths = range(math.ceil(perim/4), perim/2)
for l in lengths:
if l*(perim/2 - l) == area:
print(l)

import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
e1 = int((perim / 4) + .25)
e2 = abs(perim**2 - (16 * area))
e3 = math.sqrt(e2)
width = e1 * e3
print(width)

Related

How to find/calculate the shaded area of this shape in python?

I'm trying to write a python program to calculate the shaded area of the circle in this picture:
[![enter image description here][1]][1]
Here is the input and output:
Enter the radius of a circle: 10
Enter the side of square :3
Enter the width of a rectangle :4
Enter the length of a rectangle :2
The shaded area is : 12.0
Here is my code:
PI = 3.14
radius = float(input("Enter the radius of a circle:"))
area = PI * radius ** 2
side = int(input("Enter the side of square:"))
area = side*side
width = float(input("Enter the width of a rectangle:"))
length = float(input("Enter the length of a rectangle:"))
area = width * length
perimeter = (width + length) * 2
print("The shaded area is :", perimeter)
Problem
You are overwriting the value of area and the previous assigned values are lost.
Example
area = input('enter first value')
10
# the value of area is 10
area = input('enter second value')
3
# the value of area is now 3 and 10 is lost
However you can use area -= number or area += number to substract or add a number to the current value of the variable like so:
area = input('enter first value')
10
# the value of area is 10
area -= input('enter second value')
3
# the value of area is now 10 - 3 = 7
As correctly pointed out in the comments you should also import math and use math.pi instead of using the value 3.14
The correct output for the shaded area is:
Enter the radius of a circle:10
Enter the side of square:3
Enter the width of a rectangle:4
Enter the length of a rectangle:2
The shaded area is : 297.1592653589793
>
I would recommend solution 1 as variables should have meaningful names (unlike solution 2):
Meaningful Variable Names
and solution 3 is a bit harder to read and understand:
Make your code easy to read/understand
Solution 1 (Using different variable names)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
circle_area = math.pi * radius ** 2
side = int(input("Enter the side of square:"))
# side = 3
square_area = side * side
# but you could use square_area = side ** 2 as well
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
rectangle_area = width * length
shaded_area = circle_area - square_area - rectangle_area
print("The shaded area is :", shaded_area)
findDimensions()
Solution 2 (Updating the area variable instead of overwriting it)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
area = math.pi * radius ** 2
side = int(input("Enter the side of square:"))
# side = 3
area -= side * side
# but you could use area -= side ** 2 as well
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
area -= width * length
print("The shaded area is :", area)
findDimensions()
Solution 3 (Moving calculations to the end)
import math
def findDimensions():
radius = float(input("Enter the radius of a circle:"))
# radius = 10
side = int(input("Enter the side of square:"))
# side = 3
width = float(input("Enter the width of a rectangle:"))
# width = 4
length = float(input("Enter the length of a rectangle:"))
# length = 2
shaded_area = (math.pi * radius ** 2) - (side * side) - (width * length)
print("The shaded area is :", shaded_area)
findDimensions()

Keep on getting TypeError: unsupported operand type(s) for *=: 'function' and 'float' error for pythagorean triplet

I have been trying to make a code which deduces whether a right-angled triangle is a pythagorean triplet or not. I have then tried to draw the triangle in turtle. However, when I try and get the degrees between the base and the hypotenuse, I get this:
TypeError: unsupported operand type(s) for *=: 'function' and 'float'
This is my code:
import math
isrightangled = int(input('is your triangle right-angled? enter 1 for no. if it is, press any other number'))
if isrightangled == 1:
print('your triangle is not a pythagorean triplet.')
else:
a = int(input('Please enter the perpendicular height of your triangle.'))
b = int(input('please enter the base length of your triangle.'))
apowerof2 = a * a
bpowerof2 = b * b
cpowerof2 = apowerof2 + bpowerof2
c = math.sqrt(cpowerof2)
degrees = int(math.degrees(math.atan(a/b)))
print(degrees)
cinput = int(input('Please enter the length of the hypotenuse of the triangle.'))
if c == cinput:
print ('your triangle is a pythagorean triplet')
from turtle import *
drawing_area = Screen()
drawing_area.setup(width=750, height=900)
shape('circle')
left(90)
forward(a * 100)
backward(a*100)
right(90)
forward(b*100)
left(degrees)
forward(c*100)
done()
else:
print ('your triangle is not a pythagorean triplet.')
Any help would be greatly appreciated!
The problem is the name of the degrees variable, it collides with the turtle.degrees() function. (https://www.geeksforgeeks.org/turtle-degrees-function-in-python/)
Just change the variable name
Also, here are two notes:
there's no need to create that many variables in order to calculate c. you can just write c = math.sqrt(a * a + b * b)
left(degrees) is not enough, you need to do left(180-degrees)
here's the code after these changes:
import math
from turtle import *
isrightangled = int(input('is your triangle right-angled? enter 1 for no. if it is, press any other number'))
if isrightangled == 1:
print('your triangle is not a pythagorean triplet.')
else:
a = int(input('Please enter the perpendicular height of your triangle.'))
b = int(input('please enter the base length of your triangle.'))
c = math.sqrt(a * a + b * b)
degs = int(math.degrees(math.atan(a/b)))
cinput = int(input('Please enter the length of the hypotenuse of the triangle.'))
if c == cinput:
print ('your triangle is a pythagorean triplet')
drawing_area = Screen()
drawing_area.setup(width=750, height=900)
shape('circle')
left(90)
forward(a * 100)
backward(a*100)
right(90)
forward(b*100)
left(180-degs)
forward(c*100)
done()
else:
print ('your triangle is not a pythagorean triplet.')

I tried creating an area calculator, it keeps stating invalid syntax for a correct code

I started a project in Codeacademy to create an area calculator. However the code elif option == "T": keeps producing syntax error. I looked at the solution but it looks exactly the same. Can anyone please help?
Thanks in advance.
I've tried changing indentation and spacing and changing it from double quotes to single quotes. I even copied and pasted the solution but it still doesn't work.
# it calculates area of circle and triangle
print"Calculator, Ready!"
option = raw_input("What shape. Enter C for Circle or T for triangle: ")
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
print area
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print area
You need to indent the area calculations since they're part of the if and elif blocks. You're getting a syntax error because an elif statement must follow an if block.
Also since you're doing print area in both cases, you only need to write it once.
The important bits fixed:
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print area
In Pythhon, a elif statement can only follow a elif or if statement, but in your code, it follows a print.
You may indent or remove the two following lines:
area = 3.14159 * radius ** 2
print area
My understanding of your code makes me propose you this solution:
# ==========================================
# It calculates area of circle and triangle
# A good practice is to initialise all your variable at the begining
option = None
radius = None
area = None
base = None
height = None
print("Calculator, Ready!")
option = raw_input("What shape. Enter C for Circle or T for triangle: ")
if option == "C":
radius = float(raw_input(" What is the radius: "))
area = 3.14159 * radius ** 2
elif option == 'T':
base = float(raw_input("Base: "))
height = float(raw_input("Height: "))
area = .5 * base * height
print ("The calculated area is: {}".format(area))

How can I take cosine of a variable in python?

I am trying to make a program that will find the x and y components of an applied force at an angle. Here is what I have so far. When I run it I get an error that basically says that you cannot take the cosine of a variable and that it has to be a real number. How would I make this type of program work?
Import math
Angle = input("Enter angle:")
Force = input("Enter applied force:")
X = math.cos(angle)
Y = x * force
Print("The x component of the applied force is", y)
B = math.cos(angle)
A = b * force
Print("The y component of the applied force is", A)
Here's code after fixing capitalization and changing type of inputted values to floats:
import math
angle = float(input("Enter angle:"))
force = float(input("Enter applied force:"))
x = math.cos(angle)
y = x * force
print("The x component of the applied force is", y)
b = math.cos(angle)
a = b * force
print("The y component of the applied force is", a)

repeating pattern with variables in python

I'm trying to make a repeating pattern program in Python that asks you for how many sides you want the repeated shape to be, how many times it should be repeated and the color of the background and shape fill. It should draw the shape before turning by 360 divided by the amount of sides. However, it keeps repeating on the spot continually. My code is below.
from turtle import*
bgColor = input("What colour background do you want?: ")
fillColor = input("What colour shape fill do you want?: ")
numberOfSides = int(input("How many sides?: "))
rotationsWanted = int(input("How many rotations?: "))
rotationsCompleted = 0
def drawshape():
fillcolor(fillColor)
bgcolor(bgColor)
begin_fill()
while (rotationsCompleted < rotationsWanted):
for x in range(numberOfSides):
forward (100)
right(360/numberOfSides)
end_fill()
drawshape()
right(360/rotationsWanted)
rotationsCompleted = rotationsCompleted + 1
Try to modify the while-loop
rotationsCompleted = 0
while (rotationsCompleted < rotationsWanted):
rotationsCompleted = rotationsCompleted + 1
and after end_fill() you should go to an other position maybe using goto(100, 100) to draw the next shape at a different position.

Categories

Resources