Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics All Together Now Cleaner Code Through Refactoring

Alex Groat
Alex Groat
444 Points

def calculate_price why?

Brand new here, so am not sure if there was a lesson here I missed out on, but I thought we were writing cleaner code.

When Ken introduces calculate_price he cuts out the equation (num_tickets * TICKET_PRICE) and then uses that same equation to write more code. Well I went in and just made amount_due = (num_tickets * TICKET_PRICE) + SERVICE_CHARGE without defining calculate_price ever and it ran perfectly.

So why define calcuate_price, why not just create the constant and add it to the equation for amount_due? Is there real world application I am missing here? If the code were much larger is that going to be a necessity?

1 Answer

Hi Alex!

This logic is based on a coding principle called DRY, which stands for Don't Repeat Yourself.

The idea is: anywhere in your code, if you EVER have to REPEAT an operation, then you should create a function, which is what they used to refer to as a SUBROUTINE.

It is more obvious with more complex repeated code, but even for a simple price calculation, it has advantages.

One primary one could/would be:

Say you had to calculate the total ticket price 30 times in your code, then later you have to add tax or a service charge to all those calculations - you can make the change once in the function and it automatically updates every calculation where the function is called/used (saving you from having to comb your code and update each calculation manually).

It's very much like how TICKET_PRICE is a constant set at 10 and used all over the place in the code.

If the ticket price changes, you just update the constant, and the ticket price changes everywhere it is referenced.

Does that make sense?

I hope that helps.

Stay safe and happy coding!

Alex Groat
Alex Groat
444 Points

Yes, Peter I think I see now.

If you had used the calculation for (num_tickets * TICKET_PRICE) more than once then by defining calculate_price make it a variable and you save yourself time from adjusting the rest of your equations.

I really appreciate the detailed response. The example really helped.

Thanks Peter