Python计算圆的周长

时间:2013-05-20 01:22:45

标签: python calculator area

我正在研究python中的区域计算器,一切似乎都没问题,......直到我计算出圆周长...

有人能指出我正确的方向吗?

import math
from math import pi

menu = """
Pick a shape(1-3):
   1) Square (area)
   2) Rectangle (area)
   3) Circle (area)
   4) Square (perimeter)
   5) Rectangle (perimeter)
   6) Circle (perimeter)
   7) Quit
"""
shape = int(input(menu))
while shape != 7:
   if shape == 1:
      length = float(input("Length: "))
      print( "Area of square = ", length ** 2 )
   elif shape == 2:
      length = float(input("Length: "))
      width = float(input("Width: "))
      print( "Area of rectangle = ", length * width )  
   elif shape == 3:
      area = float(input("Radius: "))
      circumference = float(input("radius: "))
      print( "Area of Circle = ", pi*radius**2 )
   elif shape == 4:
      length = float(input("Length: "))
      print( "Perimeter of square = ", length *4 )
   elif shape == 5:
      length = float(input("Length: "))
      width = float(input("Width: "))
      print( "Perimeter of rectangle = ", (length*2) + (width*2))  
   elif shape == 6:
      circumference = float(input("radius: "))
      print( "Perimeter of Circle = ", 2*pi*radius)

   shape = int(input(menu))

3 个答案:

答案 0 :(得分:2)

您还应该考虑使用函数和dict结构,而不是使用if .. elif结构。它看起来像这样:

import math
from math import pi

def sq_area():
    length = float(input("Length: "))
    print( "Area of square = ", length ** 2 )

def sq_perim():
    length = float(input("Length: "))
    print( "Perimeter of square = ", length *4 )

def rect_area():
    length = float(input("Length: "))
    width = float(input("Width: "))
    print( "Area of rectangle = ", length * width )  

def rect_perim():
    length = float(input("Length: "))
    width = float(input("Width: "))
    print( "Perimeter of rectangle = ", (length*2) + (width*2))  

def cir_area():
    area = float(input("Radius: "))
    radius = float(input("radius: "))
    print( "Area of Circle = ", pi*radius**2 )

def cir_perim():
    radius = float(input("radius: "))
    print( "Perimeter of Circle = ", 2*pi*radius)

def bye():
    print("good-bye")

def unrec():
    print('Unrecognized command')

menu = """
   1) Square (area)
   2) Rectangle (area)
   3) Circle (area)
   4) Square (perimeter)
   5) Rectangle (perimeter)
   6) Circle (perimeter)
   7) Quit
Pick a shape(1-7):"""

shape = ''
while shape != '7':
   shape = raw_input(menu)
   {'1': sq_area,
    '2': rect_area,
    '3': cir_area,
    '4': sq_perim,
    '5': rect_perim,
    '6': cir_perim,
    '7': bye}.get(shape, unrec)()

答案 1 :(得分:1)

用radius替换变量圆周。

答案 2 :(得分:0)

是的,改变:

elif shape == 6:
  **circumference** = float(input("radius: "))
  print( "Perimeter of Circle = ", 2*pi*radius)

elif shape == 6:
  **radius** = float(input("radius: "))
  print( "Perimeter of Circle = ", 2*pi*radius)

(强调补充)