Moving functions to modules.

Learned how to move the functions in my little program out to a separate module file, and then call the functions inside of it as needed. Nice thing is that you do not have to actually import any functions that you do not need, such as ones that are only used by other functions in the same module.

The main part of the program below calls the function validate_and_execute, as well as the variable user_input_message, from the helper.py file in the functions sub-directory.

from functions.helper import validate_and_execute, user_input_mesage
#import functions.helper

user_input = 0
while user_input != "quit":
    user_input = input(user_input_mesage)
    if user_input.lower() == "quit":
        quit()
    days_and_unit = user_input.split(":")
    #print(days_and_unit)
    days_and_unit_dictionary = {"days": days_and_unit[0], "unit": days_and_unit[1]}
    #print(days_and_unit_dictionary)
    validate_and_execute(days_and_unit_dictionary)
Code language: Python (python)

The file below is the actual helper.py file.

def days_to_units(number_of_days, conversion_unit):
    if conversion_unit == "hours":
        calculation_to_units = 24
    elif conversion_unit == "minutes":
        calculation_to_units = 24*60
    else:
        return("Invalid conversion unit...")
        
    if number_of_days > 0: 
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {conversion_unit}."
    else:
        return "You did not enter a positive integer..."

def validate_and_execute(days_and_unit_dictionary):
    try:
        print(days_to_units(int(days_and_unit_dictionary["days"]), str(days_and_unit_dictionary["unit"])))
    except ValueError:
        print("Please correct your input...")

user_input_mesage = """Enter the number of days and conversion to unit (10:minutes or 20:hours).\nEnter 'quit' to exit the program: """
Code language: Python (python)

Pretty cool stuff, and can see how it would make the code more organized.

Leave a Comment

fifteen − 12 =