Your first local project
Build a study timer calculation in two files. It answers a small question: if you planned 30 minutes and completed 12, how many remain?
On this page
Write the calculation
Open the python-study folder from the installation guide. Save this code in a file called study.py.
def minutes_left(planned, completed):
return max(planned - completed, 0)
if __name__ == "__main__":
print(minutes_left(30, 12))Run .venv/bin/python study.py on macOS or Linux, or .\.venv\Scripts\python.exe study.py in PowerShell. Expect 18. The subtraction finds the remaining time. The call to max keeps it at zero when you study beyond your goal.
Test three situations
Create a second file beside the first, named test_study.py. Importing the function lets each test supply different numbers. The main guard in study.py keeps the demonstration print out of the tests.
import unittest
from study import minutes_left
class StudyTests(unittest.TestCase):
def test_partly_finished(self):
self.assertEqual(minutes_left(30, 12), 18)
def test_goal_reached(self):
self.assertEqual(minutes_left(30, 30), 0)
def test_extra_practice(self):
self.assertEqual(minutes_left(30, 45), 0)From the folder containing both files, run .venv/bin/python -m unittest -v on macOS or Linux. In PowerShell run .\.venv\Scripts\python.exe -m unittest -v. Look for Ran 3 tests and OK.
Learn from a failed test
Temporarily change the return line to return planned - completed. Run the tests again. The extra-practice test now reports -15 != 0. Read the test name, the expected value, and the actual value before changing the code. Restore the original return line and rerun all three tests.
For your own exercise, add a fourth test for a 20-minute goal with zero minutes completed. Predict its result, then run it. Continue to Your first Python program for the fundamentals behind each line.