Gary O'Neill
Gary O'Neill

Reputation: 27

Python: function, for loop, error message

I am pretty new to Python and am practicing with codeacademy, am getting a strange error message with below function. I dont understand as it looks logically and syntactically correct to me, can anyone see the issue?

def compute_bill(food):
    total = 0
    for item in food:
        total = total + item
    return total

Oops, try again.

compute_bill(['apple']) 

resulted in a

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Upvotes: 1

Views: 126

Answers (2)

saikumarm
saikumarm

Reputation: 1575

as @Rilwan said in his answer yo cannot add string with an interger. Since you are working on codeacademy, i have completed similar assignment, I believe you have to get the cost of the food that you send to the function from a dictionary and then calculate the total.

food_cost = { "apples" : 20, "oranges" : 40}
def compute_bill(food):
     total = 0
     for item in food:
         total = total + food_cost[item]
     return total
compute_bill(['apples'])

Upvotes: 1

Rilwan
Rilwan

Reputation: 2301

You cannot add a string with an integer . typeError on python Docs -typeError

call the function like below-

compute_bill([1]) 
compute_bill([10,20,30]) 

OR

apple = 10
orange = 20
compute_bill([apple,orange]) 

Upvotes: 1

Related Questions