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)
Bad
y = "something"
z = y
print(z)
Better
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
- else:
- 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.
Comments begin with the # character. Triple quotes are not actually comments - they are strings.
The best code doesn’t need comments - but comments are useful tools. The comments should give context about what you are doing.
# Don't do this
x = x + 1 # Increment x
# At least you have context now.
x = x + 1 # Compensate for border
# Best
x += 1
What does this code do?
Answer: Nothing. You should remove commented out code when you are submitting.
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.