Code is actually written for humans - not computers. Computers don’t understand python directly - they need an interpreter to convert it to instructions that the computer knows. Similiarly humans don’t automatically understand python, they need an interpreter to understand it - their brain.
The best “comment” is a cleanly laid out program.
You’re making your program easy to understand/reason with
As well as handling/considering ways in which it could fail
Aspects of style: Variable Names, Modularization, Spacing.
# Bad a, y = 25, 60 z = y asdad = "Win" print(asdad)
# Better time_left, points = 25, 60 high_score = points message = "Win" print(message)
y = "something" z = y print(z)
y = "something" print(y) # If y will never change, print("something")
# Bad if attr == True: print 'True!' if attr == None: print 'attr is None!'
# Better # Just check the value if attr: print 'attr is truthy!' # or check for the opposite if not attr: print 'attr is falsey!' # or, since None is considered false, explicitly check for it if attr is None: print 'attr is None!'
# Not great def notSoGreat(x):
- if (x == 1):
- return True
- return False
# better def better(x): return x == 1
What if you wanted to do the opposite of the conditional?
return not CONDITIONALSTATMENT
But be careful when you are chaining conditional statements.
PEP8 - is a style guide that is used for Python code and it’s worth taking a look at to see what others consider good style.
Albert Wu - who was a TA for CS61A a while ago - wrote a style guide that is really useful.
You can view it here.