Shaun Rogers
Shaun Rogers

Reputation: 21

Python: 'float' object is not subscriptable when iteration function

I am teaching myself Python and am trying out a challenge I found to create a quote program for a gardener. I have almost all of it working and have added in iteration so that the user can make more than one quote without re-starting the program.

It produces the quote perfectly the first time but on the second run it presents this error:

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

I have the following code as a function that is producing the error:

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

I have tried re-setting the local variables on the running of the function (but I didn't think this was needed as the variables should be removed from memory once the function has run).

I hope the question is clear and that I can get some insight. To re-iterate, what I want the program to do is allow me to call this function multiple times.

Upvotes: 1

Views: 3032

Answers (1)

Andr&#233; Laszlo
Andr&#233; Laszlo

Reputation: 15537

You are using the global time variable, which is initially subscriptable (probably an array). As your program continues, some other part of your code will assign a new value to time, maybe accidentally because you wrote time = some_calculation() instead of time[i] = some_calculation(), or maybe you are using the name time somewhere else without realizing it's already in use.

Do a search for all the places where you use the name time and you will probably find your error.

This is a common problem with global variables. Sometimes something updates them from another part of the code, and the error will sneak up on you like this.

Upvotes: 1

Related Questions