我编写了一个程序,该程序应该计算墙的周长,然后根据输入计算绘制该墙所需的油漆成本。
代码:
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/