Style Examples
Contents
Style Examples¶
These examples illustrate some style suggestions to help you write beautiful code. Our Python Style Guide has a much more detailed discussion of style.
Simplify Ifs returning Boolean Values¶
Don’t
def isEven(x):
if x % 2 == 0:
return True
else:
return False
Do
def isEven(x):
return x % 2 == 0
Avoid Using == to Compare to True¶
Don’t
if isEven(10) == True:
print("Yes")
else:
print("No")
Do
if isEven(10):
print("Yes")
else:
print("No")
Use And Instead of Nested Ifs When Appropriate¶
Don’t
if isEven(x):
if isEven(y):
print("Yes")
Do
if isEven(x) and isEven(y):
print("Yes")
Use Descriptive Names and Consistent Capitalization¶
Don’t
def longWords(x):
r = []
for item1 in x:
if len(item1) > 12:
r.append(item1)
return r
Do
def longWords(dictonary):
wordsFound = []
for word in dictionary
if len(word) > 12:
wordsFound.append(word)
return wordsFound
Comments Should Complement What the Code Says¶
Don’t
def longWords(dictionary):
# make an empty list
wordsFound = []
# iterate over all the words
for word in dictionary:
# test if length of the word is > 12
if len(word) > 12:
# if so, add the word to wordsFound
wordsFound.append(word)
# return result
return wordsFound
Do
def longWords(dictionary):
"""
Return a list of all words in dictionary
13 or more characters.
"""
# Iterate over all words in the dictionary,
# adding the long ones to wordsFound.
wordsFound = []
for word in dictionary:
if len(word) > 12:
result.wordsFound(word)
return wordsFound
Remove Old or Incorrect Comments From Code¶
Don’t
def cube(n):
"""Compute n^3"""
# Fill in this method
# Compute n^2
return n * n * n
# pass
Do
def cube(n):
"""Compute n^3"""
return n * n * n
Limit Lines to About 80 Characters Wide¶
(Atom has a feint white vertical line to help you keep to a reasonable width)
Don’t
def cube(n):
"""Compute n^3"""
# This is a super long comment that just goes on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on and on
return n * n * n
Do
def cube(n):
"""Compute n^3"""
# This is a super long comment that just
# goes on and on and on and on and on and
# on and on and on and on and on and on ...
# (This is even narrower than 80 chars so
# it looks nice on the web :)
return n * n * n
Fix Broken Doc Tests¶
(Atom has a feint white vertical line to help you keep to a reasonable width)
Don’t
def cube(n):
"""
Compute n^3.
>>> cube(3)
9
"""
return n * n * n
Do
def cube(n):
"""
Compute n^3.
>>> cube(3)
27
"""
return n * n * n