【发布时间】:2018-07-26 16:43:06
【问题描述】:
在我选择一个选项后,我的程序应该在我输入任何形状的单位后给我矩形、圆形或三角形的面积。但是,它不会在一个区域公式之后停止,而是继续执行所有这些公式。我该如何阻止这个?
import math
def main():
menu()
if choice ==1:
circle()
if choice == 2:
rectangle()
if choice ==3:
triangle()
def menu():
global choice
choice = int(input('choose option 1-3:'))
while choice < 1 or choice > 3:
print('error. must choose option 1-3')
choice = int(input('try again:'))
circle()
rectangle()
triangle()
def circle ():
radCir = float(input('enter radius of circle:'))
areaCir = math.pi*radCir**2
print('area of circle:',format(areaCir,'.2f'))
def rectangle():
global choice
length = float(input('enter length of rectangle:'))
width = float(input('enter width of rectangle:'))
areaRec = length * width
print('area of rectangle:',format(areaRec, '.2f'))
def triangle():
base = float(input('enter base of triangle:'))
height = float(input('enter height of triangle:'))
areaTri = base * height * .5
print('area of triangle:',format(areaTri,'.2f'))
main()
【问题讨论】:
-
circle()、rectangle()和triangle()是模块级函数调用,它们与您试图在函数内部控制的代码流完全无关(在其他换句话说,无论您在main或menu函数中做什么,它们都会被调用)。您应该根据输入调用这些函数中的一个,您已经在main()中实现了这些函数 -
这段代码不会产生你描述的错误;它会产生一个
NameError,因为你试图在它被定义之前调用circle。
标签: python function loops menu main