使用def时出现Namerror

1 投票
2 回答
761 浏览
提问于 2025-04-17 07:29

我总是收到“NameError: name 'get_length' is not defined”的错误。我的代码哪里出问题了?

def get_length_get_width_get_depth(ask_for_length,ask_for_width,ask_for_depth):

    "Ask the user for the object's length,width, and depth"

    length = raw_input(ask_for_length)
    width = raw_input(ask_for_width)
    depth = raw_input(ask_for_depth)

    return  length,width,depth

length,width,depth = get_length, get_width, get_depth("What is the length of the object?","What is the depth?", "What is the width?")

print"\nThe object's length,width, and depth is %s,%s, and %s, respectively" % (length,width,depth)

2 个回答

1

这段代码的意思是,调用一个名为`get_length_get_width_get_depth`的函数,这个函数会问你三个问题:物体的长度是多少?深度是多少?宽度是多少?

然后,这个函数会把你回答的长度、宽度和深度分别存储到`length`、`width`和`depth`这三个变量里。

这可能正是你想要的内容。

3

你没有定义 get_length 这个方法,只有 get_length_get_width_get_depth 这个方法。

可以试试:

length,width,depth = get_length_get_width_get_depth("What is the length of the object?","What is the depth?", "What is the width?")

另外,为了修正你问题中的拼写错误和不必要的代码,看看这个完整的示例:

def get_length_get_width_get_depth(ask_for_length,ask_for_width,ask_for_depth):

    "Ask the user for the object's length,width, and depth"

    length = raw_input(ask_for_length)
    width = raw_input(ask_for_width)
    depth = raw_input(ask_for_depth)

    return  length,width,depth

response = get_length_get_width_get_depth("What is the length of the object?",
                                          "What is the depth?",
                                          "What is the width?")

print "\nThe object's length,width, and depth is %s,%s, and %s, respectively" %\
        response

撰写回答