python help on making the program accept other values?

Find the area and perimeter of a rectangle

import math

class Rectangle(object):
"""A 2D Recangle"""

def init(self, width = 1, height = 2):
self.width = width
self.height = height

def Perimeter(self):
"Return the Perimeter of the rectangle"
return (2 * self.width) + (2 * self.height)

def Area(self):
"Return the area of the rectangle"
return self.width * self.height

print("Enter your values")
width = input("width " "")
hieght = input("hieght " "")

R1 = Rectangle(1, 2)

print ('R1:', R1.Perimeter(), R1.Area())

here is what i have but i can not get the program to accept other values so i only get the the results from the default values.

Please enter your code in a code area to preserve the indentations.

Try:
R1 = Rectangle(width, height)
after your input statements

Edited 4 Years Ago by Lardmeister

In the future, please use the 'code' menu button at the top of the editing window to paste in code samples. By default, the forum software does not retain indentation, which makes reading Python code especially difficult.

As it happens, the causes of the problem are plain to see. First off, you omitted the double-underscores around the __init__() method, which means that it is just an ordinary method of that name, not the constructor as you intended. This is a common enough error, so don't feel too put out about it. The second issue is that you are reading the integer values in using input() function; in Python 2.x, this would work (though it is dangerous because it evaluates the input as a Python statement), but in Python 3.x, the input() function only reads in strings. You will need to convert the strings to integers before passing them to the c'tor. Finally, the values you are passing to the c'tor are the same as the default values; you will want to use the values you've just read in instead. Thus, the code ought to look something like this:

class Rectangle(object):
    """A 2D Rectangle"""

    def __init__(self, width = 1, height = 2):
        self.width = width
        self.height = height

    def Perimeter(self):
        "Return the Perimeter of the rectangle"
        return (2 * self.width) + (2 * self.height)

    def Area(self):
        "Return the area of the rectangle"
        return self.width * self.height

print("Enter your values")

width = 0
height = 0

# read in the input and see if it will convert to int values
# if not, repeat
while width == 0 or height == 0:
    try:
        width = int(input("width " ""))
        height = int(input("height " ""))
    except:
        width = height = 0

R1 = Rectangle(width,  height)

print ('R1:', R1.Perimeter(), R1.Area())

HTH.

This article has been dead for over six months. Start a new discussion instead.