LEARN PYTHON 3 Basta Fazoolin not working

I get “TypeError: ‘float’ object is not iterable” when I run the below code

class Menu: def __init__(self, name, items, start_time, end_time): self.name = name self.items = items self.start_time = start_time self.end_time = end_time def calculate_bill(self, purchased_items): bill = 0 for item in purchased_items: bill += item print(bill) def __repr__(self): return self.name + ' menu avaible from ' + self.start_time + " - " + self.end_time brunch = { 'pancakes': 7.50, 'waffles': 9.00, 'burger': 11.00, 'home fries': 4.50, 'coffee': 1.50, 'espresso': 3.00, 'tea': 1.00, 'mimosa': 10.50, 'orange juice': 3.50 } brunch_menu = Menu("Brunch", brunch, "11am", "4pm") brunch_menu.calculate_bill(brunch.values()) #code works - adds up to 51.5 brunch_menu.calculate_bill(brunch['tea']) #code does not work, python will not add or display value

notice that the code “brunch_menu.calculate_bill(brunch.values())” succesfully returns 51.5 because it is iterating over and adding float numbers but notice that the code “brunch_menu.calculate_bill(brunch[‘tea’])” returns “TypeError: ‘float’ object is not iterable” because python refuses to iterate over float numbers. If Python can iterate over float numbers why does it refuse to do so in the second code?

brunch_menu.calculate_bill(brunch.values()) #code works 51.5
brunch_menu.calculate_bill(brunch['tea'])  #code does not work

In the first one, brunch is a dictionary, and bruch.values() is an iterator that can be used to iterate through all the values of the dictionary.
In the second one, brunch[tea] is a float - which is not iterable.

You’d have to modify your calculate_bill method to accept floats (and not try to iterate through them) for it to work for floats.

  def calculate_bill(self, purchased_items):
    if (isinstance(purchased_items, float)):
      return purchased_items
    bill = 0
    for item in purchased_items:
      bill += item
    print(bill)
1 Like

Thanks! I think I understand. So floats can be added together no problem, but floats cannot be iterated over. When Python is using the first line of code isn’t it iterating over the dictionary of floats though?

On the first line, its iterating through values of the dictionary. Each of the values is a float.

Hmm, “tea” is the key for a float so it looks like the float should be seen by python. It looks like Python should be able to add it since “tea” is a float number. Thats what I can’t figure out, since “tea” is the key for a value float that is a float Python should see the float value and add or display it unless Python doesn’t iterate over keys for their values. It looks like it doesn’t iterate over keys for values?

python can iterate over the keys of a dictionary
but
brunch.values() gives you an iterator for the values, not the keys
of the brunch dictionary

Ok makes sense thanks!