Reputation: 21
Write a python program that compute the volume and surface area of a sphere with a radius r , a cylinder with a circular base with radius r and height h , and a cone with a circular base with radius r and height h . Place them into a geometry module. Then write a program that prompts the user for the values of r and h , calls the six functions, and prints the results.
Here is my code
from math import sqrt
from math import pi
# FUNCTIONS
def sphere_volume(radius):
return 4/3 * pi * (radius ** 3)
def sphere_surface(radius):
return 4 * pi * radius ** 2
def cylinder_volume(radius, height):
return pi * radius ** 2
def cylinder_surface(radius, height):
return pi * radius ** 2 * 2 * pi * radius * height
def cone_volume(radius, height):
return 1/3 * pi * radius ** 2 * height
def cone_surface(radius, height):
return pi * radius ** 2 + pi * radius * sqrt(height ** 2 + radius ** 2)
# main
def main():
radius = input("Radius>")
height = input("Height>")
print("Sphere volume: %d" %(sphere_volume(radius)))
print("Sphere surface: %d" %(sphere_surface(radius)))
print("Cylinder volume: %d" %(cylinder_volume(radius, height)))
print("Cylinder surface area: %d" %(cylinder_surface(radius, height)))
print("Cone volume: %d" %(cone_volume(radius, height)))
print("Cone surface: %d" %(cone_surface(radius, height)))
# PROGRAM RUN
if __name__ == "__main__":
main()
I am getting an error
return 4/3 * pi * (radius ** 3)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
Can someone please help me with what I am doing wrong?
Upvotes: 1
Views: 4036
Reputation: 6826
What the error message
unsupported operand type(s) for ** or pow(): 'str' and 'int'
means is that the things your code is telling the ** operator to operate on, i.e. radius and 3, aren't compatible with for the ** operator. In particular raising a string (str) to a power doesn't make much sense, does it?
This is because input() returns a string.
To do numeric operations on the value of radius, you have to convert the string to a number. Look at built in function float(), see https://docs.python.org/2/library/functions.html#float and while you're there have a look at some of the other built in functions.
Upvotes: 1
Reputation: 138
Parse the input like this:
# main
def main():
radius = float(input("Radius>"))
height = float(input("Height>"))
It worked for me.
Upvotes: 5