python - 如何修复 UnboundLocalError 错误?

标签 python

我编写了一个程序,该程序应该计算墙的周长,然后根据输入计算绘制该墙所需的油漆成本。

代码:

def main():
length = float(input('Enter length: ')) #Get length.
width = float(input('Enter width: ' )) #Get width.
height = float(input('Enter height: ')) #Get height.
Paint_cost()
def Paint_cost (length, width, height): #Find total paint cost.
    perimeter = length + width *4 #Find perimiter.
sq_ft = perimeter * height #Find total sq. ft. amount.
Paint = sq_ft / 300 #Calculate paint gallons to nearest int.
round(Paint)
Total= Paint*40 #Calculate total cost.
return total #Display total.

main()

然而Python一直提示“UnboundLocalError:赋值前引用了局部变量‘Paint_cost’”。我在这里做错了什么?

最佳答案

您遇到一些问题:

  • 首先,您在 main() 内定义函数 Paint_cost()。您可以在 main() 之外定义它,只要在调用 main() 函数之前定义它,它就能正常工作。
  • 其次,return 从函数返回一个值,而不是打印它。
  • 第三,您的缩进已关闭。无论其他两个错误如何,如果您尝试运行此命令,Python 都会引发 IndentationError
  • 第四,total未定义(您将其写为Total。)
  • 最后,您将在不带任何参数的情况下调用 Paint_cost()。您需要使用 Paint_cost(length, width, height) 调用它。

此代码在 Python 3 中完美运行:

def Paint_cost (length, width, height): #Find total paint cost.
    perimeter = length + width * 4 #Find perimiter.
    sq_ft = perimeter * height #Find total sq. ft. amount.
    Paint = sq_ft / 300 #Calculate paint gallons to nearest int.
    int(Paint)
    total = Paint*40 #Calculate total cost.
    return total #Display total.
def main():

    length = float(input('Enter length: ')) #Get length.
    width = float(input('Enter width: ' )) #Get width.
    height = float(input('Enter height: ')) #Get height.
    print(Paint_cost(length, width, height)) # Print the cost of the paint.

main()

这个适用于 Python 2:

def Paint_cost (length, width, height): #Find total paint cost.
    perimeter = length + width * 4 #Find perimiter.
    sq_ft = perimeter * height #Find total sq. ft. amount.
    Paint = sq_ft / 300 #Calculate paint gallons to nearest int.
    int(Paint)
    total = Paint*40 #Calculate total cost.
    return total #Display total.
def main():

    length = float(input('Enter length: ')) #Get length.
    width = float(input('Enter width: ' )) #Get width.
    height = float(input('Enter height: ')) #Get height.
    print Paint_cost(length, width, height)  # Print the cost of the paint.

main()

在此代码中,print 是 Python 2 和 3 之间的唯一更改。该函数在任一版本中都无需 print 即可工作。
如果有问题请告诉我。

关于python - 如何修复 UnboundLocalError 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29707696/

相关文章:

python - Airflow - ModuleNotFoundError : No module named 'kubernetes'

python - 在numpy的二维数组中的特定位置插入一行?

python - 如何相对于另一个相同大小的数据帧反转数据帧?

python - 如何在 Django REST 框架中返回自定义 JSON

python - 如何修复 "[rospack] Error: package ' 未找到 my_package'

javascript - 用python抓取javascript生成的html

python - 在 Keras 中,如果 samples_per_epoch 小于生成器的 'end'(自行循环),这会对结果产生负面影响吗?

python - 在 Python 3 中 pickle 关键字参数

python - 在一个大的 numpy 数组中重新排列行会将一些行归零。如何解决?

python - 将 Ruby 中的 json 响应移植到 Python