-2

I have been trying to create a program that calculates and records calories contained in certain meals, and I have a class named 'Food' which I would like to create instances of by user input. I have done a good lot of searching and haven't found any way I can do so.

Currently I have got around the problem by creating a list, like so;

ingredients.append(Food(food_name, calories, protein, fat, quantity))

The problem is that I now have to reference food by index in that list, as opposed to by name, which may be inconvenient later in the program.

I would like to do something like this;

food_name = input("Enter the food's name: ")
food_name = Food(calories, protein, fat, quantity)

But this just reassigns the variable food_name without the input.

Surely it is possible to create an instance by user input. Would appreciate any solutions! :)

2 Answers2

0

Instead of appending to a list of Foods, add them to a dict. The key will be the food name, and inserting the same name twice will be an error (you will have to code this yourself, because a dict will happily overwrite an existing item).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

Use a dictionary.

foods = {}
food_name = input("Enter the food's name: ")
foods[food_name] = Food(calories, protein, fat, quantity)
Clockwork
  • 53
  • 7
  • Thank you very much. I should mention that i am fairly new to programming, so thanks for bothering to answer a simple question! – Michael Tracey Jun 06 '17 at 12:04