gpt4 book ai didi

Python:迭代函数时 'float'对象不可下标

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:40 25 4
gpt4 key购买 nike

我正在自学 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

我尝试在函数运行时重新设置局部变量(但我认为不需要这样做,因为函数运行后变量应该从内存中删除)。

我希望问题很清楚并且我能得到一些见解。重申一下,我希望程序做的是允许我多次调用这个函数。

最佳答案

您正在使用全局time变量,该变量最初是可下标的(可能是一个数组)。随着程序的继续,代码的其他部分将为 time 分配一个新值,这可能是意外的,因为您编写了 time = some_calculation() 而不是 time[ i] = some_calculation(),或者您可能在其他地方使用名称 time 而没有意识到它已被使用。

搜索所有使用名称 time 的地方,您可能会发现错误。

这是全局变量的常见问题。有时某些东西会从代码的另一部分更新它们,并且错误会像这样悄悄出现在您身边。

关于Python:迭代函数时 'float'对象不可下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31670890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com