100 days of code: Day 15 - functions

Last modified on 2020-06-23

Source: 100-days-of-code.

Putting blocks of code inside functions that have parameters defined inside brackets that accept arguments. Make a python program easier to read and debug.

I have enough concepts now in my toolkit to start work on a program I have in mind. For the past few years, I have maintained a logfile where I periodically record my weight and the respective date it was measured. I want to write a program that will scan the file, find all these date + weight patterns, and output all the matches (as columns of data, as a graph, etc).

I create two files: datetag.py as a module of functions that I import into dates_weights.py and use to find my desired patterns.

Sample setup for datetag.py

def make_list(source_file, date_regex, tag_regex):
    """Search file for date and tag regex values. Return a list of
    matching dates and their associated tags.
    """
    print(source_file, date_regex, tag_regex)

… and for dates_weights.py

#!/usr/bin/env python3
#
# Retrieve calendar dates and their associated weight data from a logfile.
import datetag as dt

dt.make_list('foo.txt', 'dddd-dd-dd', 'nn')

Nothing useful yet. This code simply confirms that import and using the sole function works …

$ ./dates_weights.py foo.txt
foo.txt dddd-dd-dd nn

Happy hacking!