In the context of this exercise that introduces comments, where should comments be added to the code? Can I just add comments to every line of code to be safe?
Answer
Generally, comments should only be added to pieces of code that would not be obvious to others who are reading it. Adding comments to every line of code is usually not necessary, and having too much text in a file can overcrowd it, ultimately making it harder to work with or understand.
Comments help provide context for why a particular piece of code was written in that way, and also help others understand the code itself faster. Comments are typically added above the code they are describing.
# When hitpoints are below 5% and shields are gone, self-destruct.
if hp < 5 and shields == False:
self_destruct()
That’s where the comment is useful. The computer just sees 5 as an integer. From the comment we can see that 5% is the threshold for the potential invocation of self_destruct(), so it would be logical to assume that the maximum possible value of hp is 100. Therefore, 5 is equivalent to 5%. At least that’s my impression.
Normally, comments in Python are only added whenever and wherever you need them. They can be used for different purposes, and yes, you can add comments to every line, or above a set of lines to know what it happening.
Do you mean that when you have this in the middle panel:
… and then press “Run”, there is nothing but a black screen in the right-hand panel?
That is the expected behavior. The purpose of the # tag is to tell Python to ignore everything after it. The next line, persnickety_count = 0, initializes a variable, but does not call for anything to be printed or otherwise sent to the screen.
So when the script runs, Python ignores the comment (# and after), then does the variable assignment, then halts, just as requested.
If you’d like to see something on the screen, type on a new line (where the cursor is shown above):
Comments typically belong at the top of a functions, class, or file. If it becomes obvious the programmer did not completely understand the problem you end up with “Shotgun Surgery”. Comments when and whereever, rewrite the code for your own sake. If you are given that much time.