Use constants, e.g., in random_equation
rather than do something like
choice("+-*")
the string “+-*” is best as a constant at the top of the file, e.g.,
OPERATORS="+-*"
DRY it up in if-else statements
If the same code appears in all of the branches of a conditional statement, you can DRY it up, by having one instance of the code after (or before) the conditional. For example:
if True:
print("True")
guess = input("Make a guess: ")
else:
print("False")
guess = input("Make a guess: ")
should be rewritten as:
if True:
print("True")
else:
print("False")
guess = input("Make a guess: ")
Global variables
Unless there is a compelling reason we don’t want to use global variables, that is variables defined outside the function (that are not constants). Global variables can easily create hard to reason about bugs. For example, the following is valid, but not best practices:
def noargs():
print("A global:", my_global)
my_global = 4
noargs()
If a function needs values from “outside” the function, they should be made parameters.
For example, you don’t want to define a variable in your `if name == “main” statement and then use that variable in a function. Gradescope does not execute the code in the if statement and so that variable is undefined when the function executes.
“Returns” in Docstrings
Remember that return has a specific meaning in Python. If a function does
not return a value (e.g., for query_equation
do not specify a return value in
the Docstring). Any actions the function performs should be described in
the initial sentences.
Normalize user input like “yes”.
If we don’t care about “yes” vs “YES” vs “Yes”, then normalize the value before comparison, e.g.,
answer = input("A question ... [yes/no]?").lower()
if answer == "yes":
...