0

我对编码比较陌生,所以请在这里帮助我。代码只会运行到第 5 行。这段代码可能是一个通通的,但请幽默我。

编辑:没有例外,没有任何反应。在要求我在 1 和 2 之间进行选择后,代码就停止了。

print('This program will tell you the area some shapes')
print('You can choose between...')
print('1. rectangle')
print('or')
print('2. triangle')

def shape():
    shape = int(input('What shape do you choose?'))

    if shape == 1: rectangle
    elif shape == 2: triangle
    else: print('ERROR: select either rectangle or triangle')

def rectangle():
    l = int(input('What is the length?'))
    w = int(input('What is the width?'))
    areaR=l*w
    print('The are is...')
    print(areaR)

def triangle():
    b = int(input('What is the base?'))
    h = int(input('What is the height?'))
    first=b*h
    areaT=.5*first
    print('The area is...')
    print(areaT)
4

2 回答 2

11

您的问题是您已将代码放入函数中,但从未调用它们。

定义函数时:

def shape():
    ...

要运行该代码,您需要调用该函数:

shape()

请注意,Python 按顺序运行代码 - 因此您需要在调用它之前定义该函数。

还要注意,要调用一个函数,你总是需要括号,即使你没有传递任何参数,所以:

if shape == 1: rectangle

什么都不会。你想要rectangle()

于 2012-06-22T17:31:45.463 回答
0

更好的编码风格是将所有内容都放在函数中:

def display():
    print('This program will tell you the area some shapes')
    print('You can choose between...')
    print('1. rectangle')
    print('or')
    print('2. triangle')

def shape():
    shap = int(input('What shape do you choose?'))
    if shap == 1: rectangle()
    elif shap == 2: triangle()
    else:
        print('ERROR: select either rectangle or triangle')
        shape()


def rectangle():
    l = int(input('What is the length?'))
    w = int(input('What is the width?'))
    areaR=l*w
    print('The are is...')
    print(areaR)


def triangle():
    b = int(input('What is the base?'))
    h = int(input('What is the height?'))
    first=b*h
    areaT=.5*first
    print('The area is...')
    print(areaT)

if __name__=="__main__":
    display() #cal display to execute it 
    shape() #cal shape to execute it 
于 2012-06-22T17:52:21.107 回答