Tried to write an Object Oriented Python program to calculate volume of cylinder
I tried to write an OOPS python program to calculate the volume of cylinder but when I run my code I get"Process returned 0". I need to define class "Cylinder", take input from the user. Below is my code. What am I doing wrong?
from math import pi
# FUNCTIONS
def cylinder_volume(radius, height):
return ((pi * (radius ** 2))*height)
# main
def Cylinder():
radius = float(input("Radius="))
height = float(input("Height="))
print("Cylinder volume: %d" % (cylinder_volume(radius, height)))
# PROGRAM RUN
if __name__ == "__Cylinder__":
Cylinder()
Solution 1:
Here's how you would do that in a object-oriented way. You define a Cylinder object, which owns the radius and the height. It's up to the caller to do the I/O; the object only holds the state and has methods. Then, the object has a volume
method that returns the cylinder volume.
And the __name__
variable when you run a Python script is always "__main__"
.
import math
class Cylinder():
def __init__(self, radius, height):
self.radius = radius
self.height = height
def getVolume(self):
return math.pi * (self.radius ** 2) * self.height
if __name__ == "__main__":
radius = float(input("Radius="))
height = float(input("Height="))
cyl = Cylinder(radius, height)
print("Cylinder volume:", cyl.getVolume())