Skip to content

Instantly share code, notes, and snippets.

@DavidGinzberg
Created October 10, 2019 19:25
Show Gist options
  • Save DavidGinzberg/0413c1eb85d6ec3800ba675004592d22 to your computer and use it in GitHub Desktop.
Save DavidGinzberg/0413c1eb85d6ec3800ba675004592d22 to your computer and use it in GitHub Desktop.
A set of examples of common over-complicated programs, and the simpler alternatives (Python edition)
##
# Any conditional expression evaluates to either `True` or `False`, if you want to return a boolean value
# based on a conditional expression, you can just use that expression, without an if/else block
##
# The common mistake (overly verbose and overcomplicated):
def isSameNumber(x, y):
'''
Returns True if (and only if) x and y are equivalent; false otherwise
'''
if x == y:
return True # Only runs if `x == y` evaluates to `True`
else:
return False # Only runs if `x == y` evaluates to `False`
# The better, simpler way to do it:
def isSameNumber(x, y):
'''
Returns True if (and only if) x and y are equivalent; false otherwise
'''
return x == y
# Summary: any time you have code like:
# ```
# if blah:
# return True
# else:
# return False
# ```
# it can be simplified to just: `return blah`
##
# Overly Specific elif conditions -- any elif can safely assume that the preceding if (or elif) condition is false
##
# The common mistake
if x < 10:
print("Single Digits!")
elif x < 100 and x >= 10: # We already know `x >= 10` is true if we get to this line because `x < 10` was false
print("Double Digits!!")
elif x >= 100: # Same here, we already know `x >= 100` is true if we got here because `x < 100` was false
print("Triple Digits!!!")
# The better, simpler way:
if x < 10:
print("Single Digits!")
elif x < 100: # We can assume `x >= 10` is true if we get here
print("Double Digits!!")
else: # we know `x >= 100` is true if we got here because `x < 100` was false. We only need an `else` at this point
print("Triple Digits!!!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment