天天看點

python輸入半徑計算公式_python練習:取輸入半徑的周長和面積

1樓:tim_spac 發表于 2014-07-23 14:57

import math

PI = math.pi

def getInteger(prompt="Enter an integer: ",

failprompt="Input should be an integer.",

default=None,

checker=None,

):

while 1:

try:

got = int(raw_input(prompt) or default)

if checker is None or \

(callable(checker) and checker(got)) or \

(isinstance(checker, set) and got in checker) or \

(isinstance(checker, tuple)

and len(checker)==2

and checker[0] <= got <= checker[1]):

return got

print(failprompt)

except:

print(failprompt)

class Circle:

def __init__(self, radiu):

self.radiu = radiu

def area(self):

return self.radiu ** 2 * PI

def circumference(self):

return 2 * PI * self.radiu

def __getIntegerTester__():

code = getInteger("Enter code:")

print("we got your code: %d" % code)

year_range = (1970, 2199)

year = getInteger("Enter year:",

checker=year_range,

default=2014,

failprompt="year should between between %d ~ %d" % year_range

)

print("we got your year: %d" % year)

month = getInteger("Enter month:",

checker=lambda x: (1 <= x <= 12),

failprompt="the month should an integer between 1 and 12")

print("we got your month: %d" % month)

categories = set(range(5))

category = getInteger("Enter category id:",

checker=categories ,

failprompt="the category should in set %r" % categories )

print("we got your category: %d" % category)

if __name__ == "__main__":

while 1:

radiu = getInteger()

if radiu <= 0:

break

circle = Circle(radiu)

print "The circumference is: %.2f, the area is: %.2f" % (

circle.circumference(), circle.area()

)