Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Letter Game App Letter Game Refinement

Ben Hedgepeth
seal-mask
.a{fill-rule:evenodd;}techdegree
Ben Hedgepeth
Python Web Development Techdegree Student 10,287 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.

1 Answer

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Ben;

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?

Ken

Yipeng Wang
Yipeng Wang
3,211 Points

Nice explanation ! lesson learnt for me :)