[Tutor] FUNCTIONS vs. CLASSES (early beginner questions)

Rafael Knuth rafael.knuth at gmail.com
Tue Mar 28 12:45:47 EDT 2017


Question: When should I use functions?
When should I use classes?

I wrote my program twice: as a function and as a class (I did so for
educational purposes, to better understand both concepts).

Both programs do exactly the same, and the work neatly. Can you advise
when I should use functions and when it's appropriate to make use of
classes?
Any feedback rgrd. my code? Anything I can improve? Thanks!

# FUNCTION

def ManageFood():
    shopping_list = []
    prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ")
    food = input(prompt)

    while food != "quit":
        shopping_list.append(food)
        food = input(prompt)

    print("These are your foods on your shopping list: %s." % ",
".join(shopping_list))
    eat_food = []
    store_food = []
    for food in shopping_list:
        print("You bought: %s. " % (food))
        prompt = input("What would you like to do with it?\nEnter
'eat' or 'store'. ")
        if prompt == "eat":
            eat_food.append(food)
        elif prompt == "store":
            store_food.append(food)
    print("Food for instant consupmtion: %s." % ", " .join(eat_food))
    print("Food for storage: %s." % ", " .join(store_food))

ManageFood()



# CLASS

class FoodManager:
    def __init__(self):
        self.shopping_list = []
        self.user_input = ("Which foods would you like to
purchase?\nEnter 'quit' to exit? ")
        self.eat_food = []
        self.store_food = []
        self.user_choice = ("What would you like to do with it?\nEnter
'eat' or 'store'. ")

    def purchase_food(self):
        get_food = input(self.user_input)

        while get_food != "quit":
            self.shopping_list.append(get_food)
            get_food = input(self.user_input)

        print("These are your foods on your shopping list: %s." % ",
".join(self.shopping_list))

    def manage_food(self):
        for item in self.shopping_list:
            print("You bought: %s. " % (item))
            eat_or_store = input(self.user_choice)
            if eat_or_store == "eat":
                self.eat_food.append(item)
            elif eat_or_store == "store":
                self.store_food.append(item)
        print("Food for instant consumption: %s." % ", ".join(self.eat_food))
        print("Food for storage: %s." % ", ".join(self.store_food))

if __name__ == "__main__":
    my_food = FoodManager()
    my_food.purchase_food()
    my_food.manage_food()


More information about the Tutor mailing list