Int and 'str' concatenation error help in need!


#1



https://www.codecademy.com/en/courses/python-beginner-en-IZ9Ra/2/2?curriculum_id=4f89dab3d788890003000096

Oops, try again. compute_bill(['apple']) resulted in a TypeError: unsupported operand type(s) for +: 'int' and 'str'

successful execution of the for loop is expected


shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}
    
prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

# Write your code below!
def compute_bill(food):
    total = 0
    for item in food:
        total = item + total
    return total


#2

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

Let's take your code line-by-line, assuming we call compute_bill(shopping_list).

First, the total is set to 0, as it should be. Then a for loop is called, which takes each item in shopping_list and adds it to the total.

The reason this doesn't work is because you end up with, for example, total = "banana" + 0. You can't add strings to integers.

What you need to do is link the items in shopping_list to those in prices. Recall that you can access an object like so:

banana_price = prices["banana"]

So using item from your for loop, you can access the price using prices[item].

Hope this helps!


#3

thank you nedwards :slight_smile: :slight_smile: yes it helps..


#4

If you need extra help, you can maybe check this out: https://www.youtube.com/watch?v=HS4iN4-SdHo&index=10&list=PLHdCowjFIBmI1UV60W1TVa7l91Psnw73E&safe=active
:wink:


#5

Hi. This did help but also confuses me a little. Doesn't Python take scoping into consideration or is the default scoping across a script?


#6

Hi,since the exercise asks to generalize it for any list.How should we approach it?