我正在教自己Python并且正在尝试挑战我发现为园丁创建一个引用程序。我几乎所有的工作都在迭代中添加,这样用户可以在不重新启动程序的情况下制作多个引号。
它首次完美地生成报价,但在第二次运行时它会出现此错误:
Traceback (most recent call last):
File "/Users/shaunrogers/Desktop/Plymstock Prep/GCSE CS/SOL/Controlled Assessment/Sample Papers Solutions/gardening Task 2.py", line 105, in <module>
lawn = m2_items("lawn",0)
File "/Users/shaunrogers/Desktop/Plymstock Prep/GCSE CS/SOL/Controlled Assessment/Sample Papers Solutions/gardening Task 2.py", line 23, in m2_items
minutes = area*time[index]
TypeError: 'float' object is not subscriptable
我将以下代码作为产生错误的函数:
def m2_items (item,index):
global costs, time, LABOUR
length = int(input("How long is the "+ item+"?\n"))
width = int(input("How wide is the "+item+"?\n"))
area = length*width
cost_m2 = float(costs[index])
total_cost = area*cost_m2
minutes = area*time[index]
hours = int(minutes/60)
labour = LABOUR*hours
labour_cost=round(labour,2)
m2_details = [area, cost_m2, total_cost,hours, labour_cost]
return m2_details
我已经尝试在函数运行时重新设置局部变量(但我并不认为这是必需的,因为一旦函数运行,变量应该从内存中删除。)
我希望问题很明确,我可以获得一些见解。要重新迭代,我希望程序做的是允许我多次调用此函数。
答案 0 :(得分:1)
您正在使用全局time
变量,该变量最初是可订阅的(可能是数组)。随着程序的继续,代码的其他部分会为time
分配一个新值,可能是因为您编写了time = some_calculation()
而不是time[i] = some_calculation()
,或者您使用的是time
。 1}}其他地方没有意识到它已经在使用中。
搜索您使用名称time
的所有地方,您可能会发现错误。
这是全局变量的常见问题。有时某些东西会从代码的另一部分更新它们,而错误会像这样偷偷摸摸。