Confused about Functions - python

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.")

Related

Trigonometry: sin(x) getting negative value

I am trying to solve a homework: I am required to write a program which will calculate the length of a ladder based on two inputs, that is the desired height to be reached and the angle created by leaning the ladder toward the wall.
I used the following formula to convert degrees to radians :
radians = (math.pi / 180) * x # x is the given angle by the user.
I imported the math library as well to use its functions.
def main():
import math
print("this program calculates the length of a ladder after you give the height and the angle")
h = eval(input("enter the height you want to reach using the ladder"))
x = eval(input("enter the angle which will be created be leaning the ladder to the wall"))
radians = ( math.pi / 180 ) * x
length = h / math.sin(x)
print("the length is:", length)
main()
What exactly am I doing wrong?
I know the code is missing something and would appreciate it if someone could help me fill the gap.
You never used radians after you calculate it.
i.e. length = h / math.sin(radians)
To make crickt_007's right answer absolutely clear: radians which you did not use after you calculate it should be the argument of the sine:
length = h / math.sin(radians)
you calculate radians,thats ok,but problem is you never used that radians value. i think your code must be changed as follows :)
def main():
import math
print("this program calculates the length of a ladder after you give the height and the angle")
h = eval(input("enter the height you want to reach using the ladder"))
x = eval(input("enter the angle which will be created be leaning the ladder to the wall"))
radians = ( math.pi / 180 ) * x
length = h / math.sin(radians)
print("the length is:", length)
main()
if your both input will be 5,output is the length is: 57.36856622834928

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()

Creating an image of a triangle centered at the centroid

Excuse me as I am a little new to programming. Basically, I am assigned to "analyze" and produce an image of a triangle where the user specifies the lengths of two sides and the size of the angle between them, the program runs and finds the length of the third side as well as the two other angles (using Law of Cosines). Then I must have text outputs for all sides lengths, all angle measures (optional), and also print the area in the form of my turtle printing out "Here is your triangle \n It has an area of x square pixels" in the image as well.
Also, the triangle must have its centroid at (0,0). This is what I have so far:
import math
from turtle import*
print("This program will draw a custom triangle.")
firstside=float(input("Enter length of first side (between 10 and 400 pixels): "))
secondside=float(input("Enter length of second side (between 10 and 400 pixels): "))
includedangle=float(input("Enter the measure of the included angle in degrees (between 1 and 179): "))
print("Side lengths and angle measures:\n")
solvedthirdside=float(math.sqrt(firstside**2+secondside**2-(2*firstside*secondside*math.cos(includedangle))))
cage=Screen(); #Create screen object named cage
cage.setup(500,500) #set screen size to 500x500 pixels
Also, I am using the turtle graphics for this too.
I am really struggling with this. Some help would be greatly appreciated!
Please help! Thanks!
This is not finished, but should be a lot easier to work on now.
I have thoroughly factored it into functions and commented heavily; it should be pretty easy to understand. Hope that helps!
import math
import turtle
def get_float(prompt):
"""
Prompt for input and return it as a floating-point number
"""
while True:
try:
return float(input(prompt))
except ValueError:
pass
def third_side(a, b, C):
"""
Given a triangle defined by two sides and
the angle between them (in degrees),
return the length of the third side
"""
return math.sqrt(a**2 + b**2 - 2. * a * b * math.cos(math.radians(C)))
def get_sides():
"""
Prompt for a triangle as two sides and an angle,
calculate the length of the third side,
and return the three side lengths
"""
side1 = get_float("Length of first side (pixels, in 10..400)? ")
side2 = get_float("Length of second side (pixels, in 10..400)? ")
angle = get_float("Included angle (degrees, in 1..179)? ")
return side1, side2, third_side(side1, side2, angle)
def get_angle(opp, left, right):
"""
Given three sides of a triangle,
return the angle opposite the first side (in degrees)
"""
cos_opp = (left**2 + right**2 - opp**2) / (2. * left * right)
return math.degrees(math.acos(cos_opp))
def get_angles(a, b, c):
"""
Given three sides of a triangle,
return the three angles (in degrees)
"""
return get_angle(a, b, c), get_angle(b, c, a), get_angle(c, a, b)
def main():
print("This program will draw a custom triangle.\n")
side1, side2, side3 = get_sides()
angle1, angle2, angle3 = get_angles(side1, side2, side3)
print(
"\n"
"Sides and angles:\n"
"a = {side1:>5.1f} A = {angle1:>5.1f}\n"
"b = {side2:>5.1f} B = {angle2:>5.1f}\n"
"c = {side3:>5.1f} C = {angle3:>5.1f}\n"
.format(
side1=side1, side2=side2, side3=side3,
angle1=angle1, angle2=angle2, angle3=angle3
)
)
# Your code continues here!
if __name__=="__main_":
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))

Calculating area of a segment in a circle

You are given the diameter across, and the length of the segment or chord. The diameter for my question is 12, and the chord is 10. You have to find the height of the shaded segment, and then print the area. The original formula is A=2/3ch + h^3/2c. My classmates got 18 for the area, but when I use my code I get 41.
This is the closest picture representation I can find. However there is a dashed line from ϴ to s.
from math import sqrt
diamStr=input("Enter the length of the diameter: ")
diameter=int(diamStr)
chordStr = input( " Enter the chord length: ")
chord = int(chordStr)
radius = (diameter/2)
s = sqrt (diameter**2+chord**2)
h = (s/2-radius)
i= (2/3*chord*h)
j=(h**3/2*chord)
area = (i+j)
print (area)
Unfortunately there's something wrong with your formula but if look at the problem with some elementary mathematics you may notice that the angle ϴ can be found using the cosine rule since we know the 3 lengths (the two radius and chord length)
In Python it would be:
theta = math.acos((radius**2 + radius**2 - chord**2)/(2*radius**2))
Since the variable theta is already in radians we can use this formula to calculate the area of the segment :
which in python would be area = 1/2 * (theta - math.sin(theta)) * radius**2
Therefore after merging all of these we come up with a elegant solution:
import math
diamStr=input("Enter the length of the diameter: ")
diameter=int(diamStr)
chordStr = input( " Enter the chord length: ")
chord = int(chordStr)
radius = (diameter/2)
theta = math.acos((radius**2 + radius**2 - chord**2)/(2*radius**2))
area = 1/2 * (theta - math.sin(theta)) * radius**2
#print(round((area),2))
print(area)
If you enter diameter as 12cm and chord length as 10 you'll get 18.880864248381847 but you can round it to any number of decimal places you want by the round() function.
eg: print(round((area),2)) prints 18.88

Categories