Ben HedgepethPython Web Development Techdegree Student 10,284 Points
Knowing when and where to write functions
Not knowing when to write and invoke functions has me overwhelmed at this stage of going any further of trying to write my own programs. I'm having a difficult time of developing a thought process to increase my ability in knowing when to use functions.
Ken AlgerTreehouse Teacher
This is a great question and indeed is something that many people, including myself, struggle with at times. Functions are great for code that you will use multiple times in your applications. Think of them as the keepers of code that allow you to produce DRY (Don't Repeat Yourself) code. If you find yourself writing the same code repeatedly in your project, that's a great indication that a function is in order.
In the real world, we use similar concepts to functions as well. If you ask a waiter to bring you a glass of water, there is an internal function structure for that, right? We don't have to tell him to walk over to the counter, grab a clean glass, fill it with water, and return it to us. We've "called" the
bring_me_water function. Okay, that's perhaps not the best analogy, but it does represent how we should think in code.
If we have a bunch of actions, or lines of code, that are all grouped together to perform an action, we can put them into a function. This allows us to reuse the code later on.
Does that help at all?