Lab Aside: Disabling Testing Code
Disabling test work
When writing problem set code, unless you test all your functions via the console, you may have test invocations in your code.
For example, if you were tasked with creating a function called calculateTip, you might have the following test invocations in your file:
calculateTip(22) # Expected: 4.4 calculateTip(45.05) # Expected: 9.01 calculateTip(0) # Expected: 0
These test invocations are an important part of your work process, but they may create output that interferes with Codder.
Therefore, your problem set code should disable any test invocations. Of course, the most straightforward way to do this is simply delete any test lines.
Alternatively, you can use one of the following two methods:
Method 1. “Comment out”
def calculateTip(amount): return amount * .20 #calculateTip(22) # Expected: 4.4 #calculateTip(45.05) # Expected: 9.01 #calculateTip(0) # Expected: 0
The last three lines are effectively “turned off” because they're commented out; Python will ignore them regardless of the context in which the file is run and Otter Inspector will be happy.
Method 2. Main method
Nest any test invocations in an if statement that checks to see if
__name__ is set to
__main__. For example:
if __name__=='__main__': calculateTip(22) # Expected: 4.4 calculateTip(45.05) # Expected: 9.01 calculateTip(0) # Expected: 0
What this does:
__name__ is a special variable set by Python, and when a script is being run directly, it's set to
As a result, by nesting your test invocations in this if statement, they will only be invoked when you run your code file directly. They will not be run if your code file is imported by another file, as is the case with Otter Inspect, so once again, Otter Inspector will be happy.
Side note: Other programming languages, like Java and C, make use of this "main method" approach; so you may see it again if you continue down the CS path!
The above methods have the same effect in their ability to enable/disable your tests. Choose the one that best fits your taste.
And if you prefer to run all your test invocations from the Python console, you don't have to worry about any of this.
Table of Contents
- Part 2: Functions Exercises
- Part 3A: Turtles like Bagels
- Part 3B: Musical Motifs
- Knowledge Check