Python 3.4.1中局部变量在赋值前被引用
我正在尝试写一个程序,用来计算一个没有窗户和门的房间的油漆费用。我试过很多种方法,甚至还试着跟着一个类似的例子,但现在我真的不知道该怎么办了。我一直遇到很多错误。一开始我想让用户输入5个数据,但那没成功,所以我又试了2个输入,结果还是无法正常运行。如果能得到一些帮助就太好了!
# This program will calculate how much money
# it will cost to paint the walls of a shed
# that is rectangular in shape.
# Ask user to enter the length of each wall.
# Ask the user to enter the height of the walls.
# Calculate the square feet.
# Divide square feet by 300 (1) gallon.
import math
def main():
length = float(input('Enter the length of wall 1: '))
#L2 = float(input('Enter the length of wall 2: '))
#L3 = float(input('Enter the length of wall 3: '))
#L4 = float(input('Enter the length of wall 4: '))
height = float(input('Enter the height of the walls: '))
print('ft:', format(ft, '.2f'))
#print('The cost of the paint is $', format(cost, '.2f'))
ft, sq_ft, gal, cost = paint_cost(length, height)
def paint_cost(length, height):
ft = length * height
sq_ft = ft * height
gal = sq_ft / 300
cost = gal * 40
return ft, sq_ft, gal, cost
# the 40 is the cost of one gallon of paint.
main()
Enter the length of wall 1: 5
Enter the height of the walls: 5
Traceback (most recent call last):
File "E:\paint.py", line 38, in <module>
main()
File "E:\paint.py", line 21, in main
print('ft:', format(ft, '.2f'))
UnboundLocalError: local variable 'ft' referenced before assignment
这是我现在收到的消息,按照现在的方式。
1 个回答
3
我觉得你犯了一个简单的错误。注意到你在定义变量ft之前就试图使用"print('ft:', format(ft, '.f'))"来打印它。实际上,在你# print('The cost of..')那行下面,才是你第一次调用paint_cost这个函数。
所以你可以试试这个方法。把"print('ft:', format(ft, '.2f'))"这行代码移动到"ft, sq_ft, gal, cost = paint_cost(length, height)"下面。
这样可能就能解决你的问题了。