Search This Blog

Tuesday, July 15, 2025

Time Calculator Project (Project 2) - Scientific Computing with Python (freeCodeCamp.org)

ABSTRACT

This project introduces a Python program designed to calculate the future time after adding a specified duration to a starting time. The program accepts inputs such as a starting time in 12-hour format, a duration in hours and minutes, and optionally a starting day of the week. It then calculates the resulting time, correctly handling AM/PM conversions, day changes, and optionally returning the day of the week. The project aims to improve understanding of string parsing, arithmetic operations, conditional logic, and modular programming in Python. This task is suitable for beginner to intermediate programmers to strengthen practical coding skills.


CONTENTS

  1. ABSTRACT

  2. INTRODUCTION

  3. PYTHON CODE AND PERSONAL SOLUTION

  4. OUTPUT

  5. CONCLUSION AND DISCUSSION



1 INTRODUCTION

Calculating time after adding a duration to a starting time is a common problem encountered in daily life, such as scheduling or time management. This project focuses on creating a Python function that performs this calculation accurately, considering the 12-hour clock format and days of the week.

The function processes inputs including a start time with AM/PM, a duration in hours and minutes, and optionally a day of the week. It then returns the new time after adding the duration, along with how many days later it is, and the updated day if provided. Key programming concepts like string manipulation, arithmetic with carryover, conditional statements, and modular arithmetic are exercised in this project.


2 PYTHON CODE AND PERSONAL SOLUTION

The main function is called add_time(), designed to handle the inputs and return a formatted string representing the new time.

Key steps in the solution include:

  • Parsing the start time into hours, minutes, and AM/PM.

  • Converting the 12-hour time into 24-hour format for easier calculations.

  • Parsing the duration into hours and minutes.

  • Adding duration minutes and handling carryover to hours.

  • Adding duration hours to the starting hour, counting how many days pass.

  • Converting the 24-hour result back into 12-hour format.

  • Calculating the new day of the week if the day was provided.

  • Constructing the output string with time, optional day, and information about days passed.

Below is a simplified version of the main function implementation. It can also be accessed via my GitHub repository at TriPham2006/Time_Calculator: Python Project (problem provided by freeCodeCamp.org - from Scientific Computing with Python course):

def add_time(start, duration, day=None): # Separate strings and prepare numbers for calculation start_time, period = start.split() start_hour, start_minute = map(int, start_time.split(':')) added_hour, added_minute = map(int, duration.split(':')) # Define target hour and minute printed out # Convert start_hour to 24 hour clock format for easier calculating if period == "AM": if start_hour == 12: start_hour = 0 elif period == "PM": if start_hour != 12: start_hour += 12 # Calculate desired hour, minute, and days for output total_minutes = start_minute + added_minute total_hours = start_hour + added_hour + (total_minutes // 60) minute = total_minutes % 60 hour = total_hours % 24 n_day = total_hours // 24 # Define new periods printed out if hour < 12: final_period = "AM" elif hour >= 12: final_period = "PM" # Convert into 12 hour clock format if needed if hour > 12: hour -= 12 elif hour == 0: hour = 12 # Step 2 - Identify day in the week # Make a list of days in a week days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] # Refine format of minute unit if minute < 10: time = f"{hour}:0{minute} {final_period}" else: time = f"{hour}:{minute} {final_period}" # Define final time if day: # day.index(...) is the index of current week day within the list of days in a week start_day_index = (days.index(day.capitalize())) end_day_index = (start_day_index + n_day) % 7 end_day = days[end_day_index] # Using .capitalize() function to uppercase only the first letter of the whole word time += f", {end_day}" if n_day == 1: time += " (next day)" elif n_day > 1: time += f" ({n_day} days later)" return time print(add_time('3:30 PM', '2:12')) # 1 ➜ 5:42 PM print(add_time('11:55 AM', '3:12')) # 2 ➜ 3:07 PM print(add_time('10:10 PM', '3:30')) # 3 ➜ 1:40 AM (next day) print(add_time('11:59 AM', '12:01')) # 4 ➜ 12:00 PM *(AM→PM boundary test)* print(add_time('2:59 AM', '24:00')) # 5 ➜ 2:59 AM (next day) print(add_time('11:59 PM', '24:05')) # 6 ➜ 12:04 AM (2 days later) print(add_time('8:16 PM', '466:02')) # 7 ➜ 6:18 AM (20 days later) print(add_time('3:00 PM', '0:00')) # 8 ➜ 3:00 PM *(no change)* print(add_time('3:30 PM', '2:12', 'Monday')) # 9 ➜ 5:42 PM, Monday print(add_time('2:59 AM', '24:00', 'saturDay')) #10 ➜ 2:59 AM, Sunday (next day) print(add_time('11:59 PM', '24:05', 'Wednesday')) #11 ➜ 12:04 AM, Friday (2 days later) print(add_time('8:16 PM', '466:02', 'tuesday')) #12 ➜ 6:18 AM, Monday (20 days later)


3 OUTPUT

Below in FIGURE 3 are some example calls to the add_time() function and their outputs:


FIGURE 1. The output of add_time() after 12 tests were successfully passed.

These outputs show the time correctly updated with duration added, the period adjusted between AM and PM, and days passed clearly indicated. The function also properly calculates the new day when provided.


4 CONCLUSION AND DISCUSSION

This Time Calculator project successfully demonstrates how to handle time calculations programmatically with Python. The challenge primarily involves parsing and converting between 12-hour and 24-hour formats, performing arithmetic with carryover, and managing days passed.

Through this project, key Python concepts such as string manipulation, conditionals, modular arithmetic, and optional parameters were exercised. The function also improves user interaction by handling different input cases and formatting the output clearly.

One difficulty was ensuring the program correctly handles edge cases like noon, midnight, and multi-day durations. Careful attention to the conversion between time formats and day calculation logic was necessary to achieve the correct results.

Overall, this project is a practical exercise suitable for beginner programmers to deepen their understanding of Python and time-related problem solving. It also forms a useful base for developing more complex scheduling or calendar applications in the future.


REFERENCE

freeCodeCamp (n.d.) Build a Time Calculator Project. Available at: https://www.freecodecamp.org/learn/scientific-computing-with-python/build-a-time-calculator-project/build-a-time-calc (Accessed: 15 July 2025).


APPENDICES

Here below are pages of how I did the ideation step before starting coding. image image

Sunday, July 13, 2025

Arithemetic Formatter Project (Project 1) - Scientific Computing with Python (freeCodeCamp.org)

ABSTRACT

This project presents a Python-based solution to format simple arithmetic problems vertically and side by side. The function processes a list of addition and subtraction expressions and arranges them in a structured, readable format similar to handwritten calculations. The primary objective is to enhance understanding of string manipulation, error handling mostly by using conditional statements, and formatting in Python programming. The function also provides the option to display the results of each calculation. This task is appropriate for programming beginners and supports foundational skills in structured problem-solving.



CONTENTS

ABSTRACT

CONTENTS

1 INTRODUCTION

2 PYTHON CODE AND PERSONAL SOLUTION

3 OUTPUT

4 CONCLUSION AND DISCUSSION


 

1 INTRODUCTION


In elementary arithmetic, it is common to align numbers vertically when solving addition or subtraction problems, and even multiplication or division but in the scope of this project, only the first two methods are taken in consideration (mathantics 2012), (freeCodeCamp). This visual arrangement aids clarity and helps learners understand the computational process. Inspired by this approach, the objective of this project is to create a Python function that automatically formats a given list of arithmetic expressions in a vertical layout.
This function follows specific formatting and validation rules to ensure correct output. It offers a practical way to learn and practice Python concepts such as conditionals, loops, string formatting, and function definitions (freeCodeCamp ). This task not only enhances basic programming skills but also demonstrates how logical thinking is applied in real-world tasks.


2 PROJECT REQUIREMENT AND PYTHON CODE WITH PERSONAL SOLUTION

The python function developed is named as follows: 

arithmetic_arranger(problems, show_answers=False)


It receives a list of strings containing arithmetic problems, an optional Boolean flag that controls whether to display the answers, respectively. Moving to key steps of building the function, limiting the number of problems as for the input value is the first constraint to be met, the function checks if more than five problems are provided. If so, it returns an appropriate error message. 
Then, each problem is parsed and validated by splitting each into three parts, the first operand, the operator ('+' or '-'), lastly and the second operand. The function ensures only the operators '+' and '-' are accepted; operands contain digits only; each operand is no longer than four digits; spacing, which interpolates between two adjacent problems 4 spaces and right-alignment for all number on each line of each problem.
The function constructs four lines: Line 1 is for placing the first operand; line 2 presents the operator and second operand; line 3 is a line of dashes; line 4 is optional, which shows the results or the solution for each problem. Some of example output of the program should have the format as in FIGURE 1.

FIGURE 1. The manual ideation before coding.


The following part is pure code pasted from my source Python file. However, for more clear and readable version, it can be accessed via the following GitHub link to my pushed repository TriPham2006/Arithmetic_formatter.

def arithmetic_arranger(problems, show_answers=False):
    
    # First constraint
    if len(problems) > 5:
        return 'Error: Too many problems.'
        
    # BREAKING DOWN THE FORMAT 
    first_operands = [first_operand.split()[0] for first_operand in problems]    # List of first operands
    operators = [operator.split()[1] for operator in problems]  # List of operators
    second_operands = [second_operand.split()[2] for second_operand in problems]  # List of second operands
    
    # Constraints for input 
    for i in range(len(problems)):
        if operators[i] not in ('+', '-'):
            return "Error: Operator must be '+' or '-'."
        if not first_operands[i].isdigit() or not second_operands[i].isdigit():
            return 'Error: Numbers must only contain digits.'
        if len(first_operands[i]) > 4 or len(second_operands[i]) > 4 or len(first_operands[i]) < 1 or len(second_operands[i]) < 1:
            return 'Error: Numbers cannot be more than four digits.'
    
# BREAKING DOWN ELEMENTS OF EACH PROBLEM
    answers = [(int(first_operands[i]) + int(second_operands[i])) if operators[i] == '+' else (int(first_operands[i]) - int(second_operands[i])) for i in range(len(problems))] # List of answers
    width = [max(len(first_operands[i]), len(second_operands[i])) for i in range(len(problems))]    # Width of each problem block when formatting
    dashes = ['-'*(width[i] + 2) for i in range(len(problems))]   # List of dashes used for formatting
    
    # MODIFYING LIST1 AND LIST2 
    # Space multipliers for each line presented
    space_l1 = []   # List of space multipliers for list 1
    space_l2 = []   # List of space multipliers for line 2
    space_al = []   # List of space multipliers for answer line
    for i in range(len(problems)):
        space_l1.append(len(dashes[i]) - len(first_operands[i]))
        space_l2.append(len(dashes[i]) - len(second_operands[i]) - 1)
        space_al.append(len(dashes[i]) - len(str(answers[i])))
    
    #LINES OF OPERATIONS
    line_1 = [(' '*space_l1[i]) + first_operands[i] for i in range(len(problems))] # First operands
    line_2 = [operators[i] + (" " * space_l2[i]) + second_operands[i] for i in range(len(problems))] # Operators and second operands
    answer_line = [(" " * space_al[i]) + str(answers[i]) for i in range(len(problems))]
    
    # FORMATTING THE PROBLEMS
    # Format without answers
    arranged_format = ("    ".join(line_1) + "\n" +
                "    ".join(line_2) + "\n" +
                "    ".join(dashes)
    )
    # Format with answers included
    if show_answers:
        return arranged_format + "\n" + "    ".join(answer_line)
    else:
        return arranged_format

# TESTING CALLS
#print(arithmetic_arranger(["3801 - 2", "123 + 49"]))
#print(arithmetic_arranger(["1 + 2", "1 - 9380"]))
#print(arithmetic_arranger(["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]))
#print(arithmetic_arranger(["11 + 4", "3801 - 2999", "1 + 2", "123 + 49", "1 - 9380"]))
#print(arithmetic_arranger(["44 + 815", "909 - 2", "45 + 43", "123 + 49", "888 + 40", "653 + 87"]))
#print(arithmetic_arranger(["3 / 855", "3801 - 2", "45 + 43", "123 + 49"]))
#print(arithmetic_arranger(["24 + 85215", "3801 - 2", "45 + 43", "123 + 49"]))
#print(arithmetic_arranger(["98 + 3g5", "3801 - 2", "45 + 43", "123 + 49"]))
#print(arithmetic_arranger(["3 + 855", "988 + 40"], True))
#print(arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49", "988 + 40"], True))


 

3 OUTPUT

After writing the code by following with the project rules, the program has to be tested by calling the project defined function arithmetic_arranger() within the 10 pre-called print()s before successfully complete the project. The desired output can be referenced as follows in FIGURE 3. 

FIGURE 2. The final output on the terminal which passed all the tests of the project.


4 CONCLUSION AND DISCUSSION

This project successfully demonstrates how basic arithmetic problems can be formatted programmatically using Python. Although the mathematical operations themselves are simple, the coding process reinforces essential programming concepts, such as string manipulation, input validation, and control flow.
One of the key challenges was ensuring all formatting was consistent across varying lengths of operands. Additionally, including detailed error messages enhances the robustness and user-friendliness of the function.
Overall, this task is an effective exercise for beginner programmers and can serve as a stepping stone toward more complex text-based applications in Python.


REFERENCES

freeCodeCamp.org. Build an Arithmetic Formatter Project. [online] Available at: https://www.freecodecamp.org/learn/scientific-computing-with-python/build-an-arithmetic-formatter-project/build-an-arithmetic-formatter-project (Accessed 13 Jul. 2025).


APPENDICES

I would like to express my sincere gratitude to all the staff at freeCodeCamp for their continuous contributions in developing such a generous and educational platform. Thanks to freeCodeCamp, learners from all backgrounds can access high-quality materials and advance at their own pace, entirely free of charge. <3
On a personal note, I acknowledge that my solution may not be as clear or readable as I initially intended. Nevertheless, I believe that sharing the process, how I landed at the final result, is essential for evaluating my approach and improving my ideation skills in future projects. So, here is the final capture of this blog, a photo of my beginning ideation which was handwritten on a large wall-mounted sticker. Thank you for visiting my blog! 

FIGURE 3. The manual ideation at first stage before coding.

And yes... the photo had been taken a month ago before I started writing this blog :)))