0

我正在用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))
4

3 回答 3

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)()
于 2013-05-20T02:11:33.633 回答
1

用半径替换变量圆周。

于 2013-05-20T01:25:59.753 回答
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)

(重点补充)

于 2013-05-20T01:29:42.003 回答