【问题标题】:Function won't work, says it's not defined?功能不起作用,说它没有定义?
【发布时间】:2022-01-22 00:53:17
【问题描述】:

我正在尝试使用此代码来计算面积成本。我正在使用函数选项,但它说 cost 没有定义,我确实定义了它。

def space():
    """ This function will calculate the area of floor, that needs 
    flooring. """
    
    # asking for variables
    length =int(input('Please enter the length of the room in meters: '))
    width =int(input('Please enter the width of the room in meters: '))
    
    area=length*width
    
    return area

def flooring():
    """This function will take the flooring chosen by the user and will
    return the cost of the square meter."""
    
    while True:
        # asking for variables
        opt=int(input('Please select type of flooring: '))
        if (opt>=1 and opt<=5):
            break
        
    if (opt==1):
        price=18.75
    ...        
        
    return price
    
def cost():
    """This will calculate the cost of the flooring, and other costs, and
    will display them, aligned."""
    print(price)
    matCost=area*price
    print("$",matCost)  

###
### MAIN PROGRAM
###

while True:
    ...
    
    space()
    print()
    
    print('Types of Flooring')
    print()
    print('                Cost per sq.m.')
    print('1. Low Pile Carpet     $18.75')
    ...
    
    flooring()
    print()
    cost()

错误说,但我认为我已经定义了它。使用 opt 的 if 语句,我以为我已经定义了。

Traceback (most recent call last):
  File"main.py", line 80 in <module>
    cost()
  File"main.py", line 52 in <module>
    print(price)
NameError: name 'price' is not defined

【问题讨论】:

  • price 在哪里定义cost(或全局)?我看不到pricecost 可见的定义。就此而言,我看不到在哪里调用了 cost(),这意味着这不是 minimal reproducible example
  • @Shadow cost() 在最后一行被调​​用。但是否则你是对的,price 显然对cost() 是不可见的,而且这段代码绝对不是最小的。
  • 错误消息显示 price() 未定义,而不是 cost()。这是因为该名称的变量未在该函数中定义(也不是全局定义)。 flooring() 按该名称定义一个 local 变量,但 cost() 看不到它。
  • @wjandrea:糟糕,错过了滚动条。 :-)

标签: python function


【解决方案1】:

我想你只是忘了在def cost():上添加价格

def cost(price):
    """This will calculate the cost of the flooring, and other costs, and
    will display them, aligned."""
    print(price)
    matCost=area*price
    print("$",matCost)  

price_result = flooring()
cost(price_result)

【讨论】:

    【解决方案2】:

    因为 price 变量是在函数内部定义的,所以它不是全局的。 不要尝试直接调用价格变量,您必须调用返回所述价格变量的 floor 方法。

    def cost():
        """This will calculate the cost of the flooring, and other costs, and will display them, aligned."""
        price = flooring()
    
        # The area variable is also not defined outside of the space method so it would be a good idea to add this as well.
        area = space()
        print(price)
        matCost=area*price
        print("$",matCost)
    

    解决楼层类型重复询问问题:

    在下面的代码块中,print(flooring()) 语句正在调用 floor 函数,因此,重新运行 input()

    要解决此问题,您必须更改以下代码块: (阅读评论!)

    while True:
        ...
        
        space()
        print()
        
        print('Types of Flooring')
        print()
        print('                Cost per sq.m.')
        print('1. Low Pile Carpet     $18.75')
        ...
        
        # Set price variable to the flooring() method the first time you call it!
        price = flooring()
        print()
        cost()
    

    设置全局价格变量后,在函数中使用如图:

    def cost():
        """This will calculate the cost of the flooring, and other costs, and
        will display them, aligned."""
    
        #using the global price variable
        print(price)
        matCost=space()*flooring()
        print("$",matCost)  
    

    另外,如果您在意,请注意,当输入的地板类型不是 1 时,代码会引发错误,因此您可能想要打印类似“无效地板类型”之类的内容:

    if (opt==1):
        price=18.75
    else: 
        price="Invalid flooring type" 
    

    【讨论】:

    • 它现在可以工作了,但它要求地板的类型以及宽度和长度两次。因为我两次调用了这两个函数。有没有办法阻止它?
    • 没有错误代码。它要求长度和宽度。然后是地板的类型。然后再针对地板的类型。然后它再次询问长度和宽度,然后打印价格。
    • 是的,我意识到你的意思并更新了,(多余的电话)抱歉回复晚了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2013-02-28
    • 2018-04-04
    • 1970-01-01
    相关资源
    最近更新 更多