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

Stephen Hancock
Stephen Hancock
4,888 Points

Alternative += solution

So I understand the benefit of having a fixed value for service charge for your code going forward.

However creating the servive_charge and the function to calculate final price seems compartaively a lot of script when it could be solved by simply adding the line:

amount_due += 2

below the existing amount due calculation. Therefore just adding 2 to the amount_due.

Is this just a case of the solution in the video being better for larger programmes where you might be calling on your service charge value and calculate_total_price more often. Therefore good practice.

Or is there something wrong/bad practice about doing what I suggested?

1 Answer

Imagine a developer would read your code, specifically that bit: amount_due += 2. Having a basic command of Python, they would certainly know what you are doing: you are adding two to the amount, but why? They wouldn't be able to answer that question. They wouldn't be able to reason or make sense of the code. You want it to be readable. By promoting the variable and giving it a descriptive name, the code becomes more flexible and digestable. Global variable names, are usualy a bad idea, because they can be "accidently" mutated everywhere, and that can introduce bugs. That's also the reason why, in this case, it has been named in UPPERCASE letters, to "emulate" a constant, which is a type of variable that exists in other languages (not in Python) that can't be changed once set. Even though it doesn't exist in Python, that's what it wants to portrait - that is safe to be there, because it's not supposed to change.