Even more Python in the mix

Added a very simple while loop to the script, as well as a check for the word ‘quit’ which will exit the program cleanly. It will still catch any negative, 0, string or null (enter key with no value) and prompt to enter an integer again.

calculation_to_units = 24
name_of_unit = "hours"

def days_to_units(number_of_days):
    if number_of_days > 0:
        return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
    else:
        return "You did not enter a positive integer..."

def validate_and_execute():
    days_entry = 0
    try:
        days_entry = input("Enter the number of days, and enter 'quit' to exit the program: ")
        print(days_to_units(int(days_entry)))
    except ValueError:
        if days_entry == "quit":
            quit()
        else:    
            print("Please enter a positive integer value...")

while True:
    validate_and_execute()
Code language: Python (python)

Leave a Comment

three × two =