Its good that you're thinking about how to make the code more efficient. Kudos to you!
Yes, repeating code is a red flag that things can be simplified. But here, the code is very similar but not the same. It's only the same pattern performed on different variables. It's good that you recognize that there may be a better way, but it's also very important to recognize the difference between very similar code and identical code. In this case, if you were writing the same code over and over many more times, then it would be appropriate to write a function to do the work. But, since it's only 4 times, and they're all bunched together, this is still better. The overhead of a function would outweigh it's usefulness.
You'll learn more about code efficiency in a later lesson! ;-)
Interestingly, this is a case where the code you wrote is about as efficient as it can get. There are two lines of simple code to calculate how many of each type of coin and how much change is left. That means two calculations per coin, or 8 calculations overall.
If you were to add a loop, that would mean all the overhead of a loop, and calculations inside each pass would be multiplied by the number of passes. While it may be good practice in writing loops, adding any loops here would just make the code more complex.
In coding, simpler is usually better. There's an old programming adage, one that I usually tell myself on every project - "KISS, Keep It Simple, Stupid!" It means that if the code seems like it is getting too complicated, it's probably wrong and needs to be simplified. Complexity invites bugs.
Having said all that, the code could be simplified just a little. Pennies can be handled with one statement. Think about this. What are the possible results of x = x % 1
?
If you were ambitious, you could actually combine it with the nickels calculation, but that would be complicating things unnecessarily. KISS, right? ;-)
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)