KeysMcGee
KeysMcGee

Reputation: 17

Creating a rectangle class that accepts parameters

I am trying to create a create a rectangle class that accepts length and width as parameters. I would like the user to be able to enter a number and have python calculate the perimeter of the rectangle.

I tried using Input() to allow the user to do this, but python does not like that. I also tried using raw_input but, I received a 'this is not-defined' error.

I was hoping someone could point me in the right direction.

class circle:
  def __init__ (self):
    self.radius = 1
    self.width = 1
    self. length = 1

my_circle = circle ()
print(2 * 3.14 * my_circle.radius)
my_circle.radius = input('Input here:')
print(float(2 * 3.14 * my_circle.radius))
my_circle.radius = 48
print(2 * 3.14 * my_circle.radius)

I would like to enter length and width and have the perimeter returned. I also will do this for the area, but I should be able to replicate the perimeter code once I figure it out.

Upvotes: 0

Views: 1325

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

To begin with, you can use the __init__ constructor to pass your length and width argument instead of doing a attribute assignmnent like rectange.width = ...

So the Rectangle class will look like. You can see I am passing width and length in the constructor

class Rectangle:

    def __init__ (self, width, length):
        self.width = width
        self.length = length

    def perimeter(self):
        return 2*(self.length + self.width)

After this, you can call your class and function like so.
Here I convert the width and length to float (which you did not do in your circle class), pass them when I create the object of the class and then calculate parameter

length = float(input('enter length:'))
width = float(input('enter width:'))
rectangle = Rectangle(length, width)
print( rectangle.perimeter())

A sample run will then look like

enter length:5
enter width:10
30.0

Similarly your circle class will look like

class circle:
    def __init__ (self, radius):
        self.radius = radius

    def area(self):
        return 2*3.14*self.radius

radius = float(input("Enter radius of circle"))
my_circle = circle (radius)
print(my_circle.area())
#Enter radius of curcle1
#6.28

Upvotes: 1

Related Questions