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.


What not to do:

  • Variable names that don’t clarify: a, test, test1
  • Leaving everything as one big hunk of code.
  • Too many comments because the program is unclear.
  • Use the o and 0 or I,l,1 - leading to confusion if that’s a 0 or a 1


Useful names

  1. Have useful variable names
# Bad
a, y = 25, 60
z = y
asdad = "Win"
# Better
time_left, points = 25, 60
high_score = points
message = "Win"

Variable Names.


y = "something"
z = y


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?


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.

Where to get more information

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.