0
幫助!我明天有這個程序,要求它必須具有topLeft拐角的X,Y笛卡爾座標和bottomRight拐角的X,Y笛卡爾座標作爲raw_input。然後打印周邊,區域和這兩個位置。 但是我不能讓raw_input工作。我曾嘗試將其轉換爲整型,分割和多個賦值。具有笛卡爾座標raw_input的類矩形?
topLeft = int(raw_input ('Please enter a coordinate==>')).split()
bottomRight= int(raw_input ('Please enter a coordinate==>')).split()
class Rectangle:
def __init__(self, topLeft, bottomRight):
self.tL = topLeft
self.bR = bottomRight
def perim(self):
return (2 * (self.tL)) + (2 * (self.bR))
def area(self):
return (self.tL) * (self.bR)
def position(self):
return (self.tL, self.bR)
def __str__(self):
return "Rectangle(%s, %s)" % (self.tL, self.bR)
r1 = (Rectangle (topLeft,bottomRight))
print r1
print "Perimeter: %s" % r1.perim()
print "Area: %s" % r1.area()
print "Position: (%s, %s,)" % r1.position()
這是我最親密的嘗試,但我仍然得到錯誤:
Traceback (most recent call last):
File "C:\Users\Mary\Desktop\Python Programs\Rectangle.py", line 1, in <module>
topLeft = int(raw_input ('Please enter a coordinate==>')).split()
ValueError: invalid literal for int() with base 10: '(5,10)'
我是初學者,非常感謝您的幫助!我參加並調整了我的課堂教學方法,我將這些方法交給了其他人,但是你的教學更有意義。我沒有意識到我需要在課堂上檢查整數。它現在完美地工作。 –
處理座標的更好方法是使用'collections.namedtuple',它們是鬆散的微小* class *工廠,使它們感覺自然。如果'P'是一個名爲tuple class的點,則可以執行'top = P(x = xt,y = yt)'和'top.x top.y'。它看起來很自然。 –