Lab4 - trying to understand what I'm supposed to do - python

This is what I have to do; "Assume that you have the coordinates (x,y) of four points p1, p2, p3, and p4. Write a function name
check_is_square() that asks the user for the coordinates of those four points (total of eight integer inputs) and prints the message Yes – it is a Square if those four points can form a square on the coordinate plane and the message No – it is not a square otherwise. Call check_is_square()from the main() function."
This is the code I have currently;
import math
def check_square(x1,x2,y1,y2):
if (math.sqrt((x1 - x2)**2+(y1-y2)**2) % 2 == 0):
print("Yes - it is a square")
else:
print("No - it is not a square")
def main():
x1 = int(input("Enter coordinate 1: "))
x2 = int(input("Enter coordinate 2: "))
y1 = int(input("Enter coordinate 3: "))
y2 = int(input("Enter coordinate 4: "))
check_square(x1,x2,y1,y2)
main()

Related

Confused about Functions

So I'm currently doing an assignment for my python coding class and I have to get the area of a cylinder and I'm supposed to be using functions so it looks cleaner, but I'm not so sure how to exactly do my assignment from scratch, I've watched a lot of videos but can't really seem to understand functions, my code looks like this currently, but whenever I run my code I can't get the "def calc():" part to run, could I get some pointers please?
def info():
r = float(input("What is the radius of the cylinder? "))
h = float(input("What is the height of the cylinder? "))
print("The cylinders area is", area)
def calc():
pi = 22/7
area = ((2*pi*r) * h) + ((pi*r**2)*2)
return pi, area
info()
Don't need so many funcatin .
def info():
r = float(input("What is the radius of the cylinder? "))
h = float(input("What is the height of the cylinder? "))
calc(r,h)
def calc(r,h):
pi = 22/7
area = ((2*pi*r) * h) + ((pi*r**2)*2)
print("The cylinders area is", area)
info()
in this case I put the radius as 3 and height as 6. You need to define you variables.
Then it should work. in this case I used numpy to import an exact pi variable.
You have to put the calc() function above the info() function. You have to actually call the calc() function which will return the area of cylinder. I have provided the code below which should solve your problem. Hope you understand the code!
def calc(r, h): # Calculates the area of cylinder
pi = 22/7
area = ((2*pi*r) * h) + ((pi*r**2)*2)
return area
def info(): # Takes the radius and height from user.
r = float(input("What is the radius of the cylinder? "))
h = float(input("What is the height of the cylinder? "))
return f"The area is {calc(r, h)}"
# r = 5
# h = 10
print(info())
# using parameters in functions instead of inputs:
def info2(r, h):
return f"The area is {calc(r, h)}"
r = 5
h = 10
print(info2(r, h))
# Comparing areas of cylinders
area1 = calc(5, 10)
area2 = calc(10, 15)
if area1>area2: #Area1 is greater than Area2
print("Area1 is greater than Area2")
elif area2>area1: #Area2 is greater than Area1
print("Area2 is greater than Area1")
else: #Both are equal
print("Both are equal")
You mentioned in a comment that you wanted to input multiple cylinders and determine which was the larger one -- I think for that you want to have your function that inputs a cylinder return the cylinder itself so that it can be compared using the volume function.
from dataclasses import dataclass
from math import pi
#dataclass
class Cylinder:
radius: float
height: float
name: str
def volume(c: Cylinder) -> float:
return (2*pi*c.radius) * c.height + (pi*c.radius**2)*2
def input_cylinder(name: str) -> Cylinder:
r = float(input(f"What is the radius of the {name} cylinder? "))
h = float(input(f"What is the height of the {name} cylinder? "))
return Cylinder(r, h, name)
if __name__ == '__main__':
cylinders = [input_cylinder(name) for name in ('first', 'second')]
for c in cylinders:
print(f"The {c.name} cylinder's volume is {volume(c)}")
print(f"The bigger cylinder is the {max(cylinders, key=volume).name} one.")

Using double if statements in the same line as required

Hello dear SO members and staffs. I have been working on a project where I took the coordinates of the already drawn rectangle with the center of (0,0) coordinates. What I want to do is ask the user to put his x and y coordinates, after which it will tell you that whether if your coordinates is within the area of that or not. I have reached some of my goals, except the one that I need to ask the if statement for both of the x and y at the same time as if I will write only X statement it will display for only checking the X and not Y.
So, I need your help in how to check both of them before displaying?
(The center of the rectangle is at the (0,0) with the total length of 5 and the width of 10.)
y1 = -2.5
y2 = 2.5
x1 = -5
x2 = 5
inputX = eval(input("Please put in the X coordinate: "))
inputY = eval(input("Please put in the Y coordinate: "))
if x1<inputX<x2, y1<inputY<y2:
print("Your coordinates are in the range of the rectangle!")
else:
print("Sorry, your coordinates are not in the range of the rectangle!")
Use and to combine them:
if (x1 < inputX < x2) and (y1 < inputY < y2):
i think that will work
if (x1<inputX and inputX<x2 and y1<inputY and inpputY<y2):
print("Your coordinates are in the range of the rectangle!")
else:
print("Sorry, your coordinates are not in the range of the rectangle!")
The following code will work for only integer inputs - as it uses range function - range()
`
x1 = -5
x2 = 5
y1 = -2
y2 = 2
inputX = eval(input("Please put in the X coordinate: "))
inputY = eval(input("Please put in the Y coordinate: "))
if (inputX in range(x1,x2+1)) and (inputY in range(y1,y2+1)):
print("Your coordinates are in the range of the rectangle!")
else:
print("Sorry, your coordinates are not in the range of the rectangle!")
`
The answer before given using if condition has no problem, I am writing this to give an idea for an approach of using it using a function

Python typeerrorfloatrequiredline.20

#Python program when involved with maths
import math
def areaOfcircle(x):
#Calculate the area
area=(math.pi)*math.pow(x,2)
print(area,"is the area of your circle")
#Input used to find x
areaOfcircle(int(input("What is the radius of your circle?")))
def areaOftriangle(b,h):
area=(b+h)/2
print(area,"is the area of your triangle")
areaOftriangle(int(input("What is the base of your triangle")),int(input("What is the hight of your triangle")))
def areaOfsquare(x):
area=math.pow(x,2)
print(area,"is the area of your square")
areaOfsquare("What is the length of your square?")
flag="f"
while flag=="f":
shape=input("Which of the following shapes, Circle, Triangle or Square do you want to calculate the area of: ")
if shape=="Triangle" or "triangle":
area=areaOftriangle
print(area)
elif shape=="Square" or "square":
area=areaOfsqaure
print(area)
elif shape=="Circle" or "circle":
area=areaOfcircle(x)
print(area)
Im feeling in the mood today. I fixed your code to the desired functionality you require. :)
Mainly, you have multiple errors.
1) indentation error with your elifs.
2) argument passing error with area=areaOfcircle(x).
3) areaOfsquare("What is the length of your square?") is trying to pass a string and calculate the string.
4) Design-wise, you should be asking user input for shape first before asking for measurements.
5) if shape=="Triangle" or "triangle": should be changed to if shape.lower() == 'triangle':
import math
def areaOfcircle(x):
area=(math.pi)*math.pow(x,2)
print(area,"is the area of your circle")
def areaOftriangle(b,h):
area=(b+h)/2
print(area,"is the area of your triangle")
def areaOfsquare(x):
area=math.pow(x,2)
print(area,"is the area of your square")
flag="f"
while flag=="f":
shape=input("Which of the following shapes, Circle, Triangle or Square do you want to calculate the area of: ")
if shape.lower() == "triangle":
areaOftriangle(float(input("What is the base of your triangle? ")),float(input("What is the height of your triangle? ")))
break
elif shape.lower() == "square":
areaOfsquare(float(input("What is the length of your square? ")))
break
elif shape.lower() == "circle":
area=areaOfcircle(float(input("What is the radius of your circle? ")))
break
else:
print('No such shape, please try again')

Why won't python update function value?

I am trying to make a table in python that asks a user for a side length of a polygon and then gives the area of that polygon when it's number of sides is between 3-9. My problem is that, in the report function, I have to give a different area for each polygon with a different number of sides but when i run it, the area is always the same even when the number of sides of the polygon has changed.
import math
def main():
side_length = get_side_length()
report(side_length)
def get_side_length():
length = int(input('Enter a side length: '))
return length
def report(a):
num_sides = 2
each_area = polygon_area(a)
print('side length\t'+ 'number of sides\t'+ 'area')
while num_sides < 9:
num_sides += 1
print(a, num_sides, each_area, sep='\t\t', end='\n')
def polygon_area(sl):
for num_sides in range(3, 10):
area = (num_sides * sl * sl) / (4 * math.tan(math.pi / num_sides))
return area
main()

Why does Python suddenly stop if the input is Yes?

I'm trying to make this program in Python which asks for the surface area and volume of a cylinder. At the end, it asks the user if it wants to calculate volume/surface area. However, if they do type in Yes, nothing happens. What is wrong with my code?
Secondly, I tries using math.pi but it didn't work, what should I do.
The code is long so only scroll down to the important parts:
print("Welcome to the volume and surface area cylinder calculator powered by Python!")
response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ")
if response=="vol" or response =="SA":
pass
else:
print("Please enter a correct statement.")
response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ")
if response=="vol":
#Below splits
radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286
volume = PI*radius*radius*height
decimal_places = int(input("How many decimal places do you want it to?: "))
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places))
verify = input("Do you want to find out the surface area (type in Yes or No): ")
verify = verify.capitalize
if verify == "Yes":
radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286
SA = int(2)*PI*radius*radius+int(2)+radius*radius*height
decimal_places = int(input("How many decimal places do you want it to?: "))
print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places))
if verify == "No":
pass
if response =="SA":
#Below splits
radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286
SA = int(2)*PI*radius*radius+int(2)+radius*radius*height
decimal_places = int(input("How many decimal places do you want it to?: "))
print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places))
verify = input("Do you want to find out the volume (type in Yes or No): ")
verify = verify.capitalize
if verify == "Yes":
radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
PI = 3.141592653589793238462643383279502884197169399375105820974944592307816406286
volume = PI*radius*radius*height
decimal_places = int(input("How many decimal places do you want it to?: "))
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places))
if verify == "No":
pass
You replaced verify with a method:
verify = verify.capitalize
This'll never match either 'Yes' or 'No' because it is no longer a string. Call the method instead:
verify = verify.capitalize()
Note that your test for "No" can just be dropped, there is little point in testing for a string then just passing.
Using math.pi instead of PI otherwise works just fine:
>>> import math
>>> math.pi
3.141592653589793
>>> radius, height = 32, 15
>>> 2 * math.pi * radius ** 2 + 2 * math.pi * radius * height
9449.910701998098
>>> math.pi * radius ** 2 * height
48254.86315913922
This is my tweaked version. It avoids a lot of repetition.
from math import pi
print("Welcome to the volume and surface area cylinder calculator powered by Python!")
response = raw_input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ").lower()
while response not in ["vol", "sa"]:
print("Please enter a correct statement.")
response = raw_input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ").lower()
radius, height = [float(part) for part in raw_input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]
r2 = radius ** 2
SA = 2 * pi * r2 + 2 + pi * radius * height
volume = pi * r2 * height
decimal_places = int(raw_input("How many decimal places do you want it to?: "))
if response=="vol":
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places))
verify = raw_input("Do you want to find out the surface area (type in Yes or No): ")
if verify.lower() == "yes":
print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places))
if response =="sa":
print("The surface area of the cylinder is {0:.{1}f}cm\u00b2".format(SA, decimal_places))
verify = raw_input("Do you want to find out the volume (type in Yes or No): ")
if verify.lower() == "yes":
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimal_places))

Categories