【问题标题】:confused with def main() and def menu() order与 def main() 和 def menu() 顺序混淆
【发布时间】: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() 是模块级函数调用,它们与您试图在函数内部控制的代码流完全无关(在其他换句话说,无论您在 mainmenu 函数中做什么,它们都会被调用)。您应该根据输入调用这些函数中的一个,您已经在main() 中实现了这些函数
  • 这段代码不会产生你描述的错误;它会产生一个NameError,因为你试图在它被定义之前调用circle

标签: python function loops menu main


【解决方案1】:

这是因为您在定义函数之前调用了它们。删除定义之前对函数的调用,即删除:

circle()

rectangle()

triangle()

出现在def circle ():...上方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2010-09-16
    • 2017-03-27
    • 1970-01-01
    相关资源
    最近更新 更多