0% found this document useful (0 votes)
10 views

Programming Assignment Unit 4

Assignment

Uploaded by

htetkaungthaw27
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Programming Assignment Unit 4

Assignment

Uploaded by

htetkaungthaw27
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Programming Assignment Unit 4

Htet Kaung Thaw


CS 1101 – Programming Fundamentals
Instructor : Safia Hirari
Deadline : 12th December 2024
Programming Assignments

Assignment Instructions:

This assignment will assess your skills and knowledge in developing a function through an
incremental development process such that the debugging becomes fast. There are two parts of
this assignment, and you must submit both parts.

Part 1
You work as a software developer in a company that creates custom software solutions for
various clients. Your company has been approached by an educational client who wants to
develop a function that calculates the length of the hypotenuse of a right triangle given the
lengths of the other two legs as arguments. Your manager has instructed you to use incremental
development to create the necessary function and document each stage of the development
process. After completing the final stage of development, you have to test the function with
different arguments and record the outputs in your Learning Journal.

Stage 1 – Initial Function

In this step we will define a simple function that takes two arguments a and b which
represent respectively the lengths of the two legs of a right triangle and which returns a
placeholder value. We will not calculate the hypotenuse in this step.

def hypotenuse(a, b):

return None

Stage 2 – Input Validation

Now, let’s add input validation to ensure that a and b are non-negative numbers. We’ll
raise an exception if the inputs are invalid.

def hypotenuse(a, b):

if a<0 or b<0:

Raise ValueError(“Both ‘a’ and ‘b’ must be non-negative numbers”)

return None

Stage 3 – Calculate Hypotenuse

In this stage, we’ll calculate the length of the hypotenuse using the Pythagorean theorem:
import math

def hypotenuse(a, b):

if a<0 or b<0:

raise ValueError(“Both ‘a’ and ‘b’ must be non-negative numbers”)

c = math.sqrt(a**2 + b**2)

return c

Stage 4 – Testing

To get the output, we need to run the code. When you execute the above code, it will
print the result of hypotenuse(3, 4):
import math

def hypotenuse(a, b):


if a<0 or b<0:
raise ValueError("Both 'a' and 'b' must be non- negative numbers")

c = math.sqrt(a**2 + b**2)
return c

print(hypotenuse(3, 4)) #Testing with a=3 and b=4

The output:

Below the output to the above code with the following hypotenuse arguments, hypotenuse(5, 6):
import math

def hypotenuse(a, b):


if a < 0 or b < 0:
raise ValueError("Both 'a' and 'b' must be non-negative numbers")

c = math.sqrt(a**2 + b**2)
return c

print(hypotenuse(5, 6)) #Testing with a=5 and b=6


Below the output to the above code with the following hypotenuse arguments, hypotenuse(10,
12):
import math

def hypotenuse(a, b):


if a < 0 or b < 0:
raise ValueError("Both 'a' and 'b' must be non-negative numbers")

c = math.sqrt(a**2 + b**2)
return c

print(hypotenuse(10,12)) #Testing with a = 10 and b = 12

Part 2

You are a software developer who wants to establish yourself as a skilled and versatile
programmer. To achieve this, you have decided to create a work portfolio that showcases your
ability to develop custom software solutions. This portfolio will be your gateway to attract
potential clients and establish yourself as a freelancer.
As part of your portfolio, you plan to create your own function that does some useful
computation using an incremental development approach that will demonstrate your
programming skills and problem-solving abilities. You will document each stage of the
development process, including the code and any test input and output in your Programming
Assignment.

I will be creating a personal finance tracker where I will be demonstrating my ability to develop
a practical software solution, including various features to showcase your skills.

Stage 1 – Initial Function

Create a basic function that initializes a list to store income and expenses.

def initialize_tracker():
return {‘income’: [], ‘expenses’: []}

Stage 2 – Add Income and Expenses

Enhance the function to allow users to add income and expenses to their tracker.

def add_income(tracker, amount, description):


tracker[‘income’].append({‘amount’: amount, ‘description’: description})

def add_expense(tracker, amount, description):

tracker[‘expenses’].append({‘amount’: amount, ‘description’: description})

Stage 3 – Calculate Balance

Calculate the current balance by subtracting total expenses from total income.

def calculate_balance(tracker):

total_income = sum(item[‘amount’] for item in tracker [‘income’])

total_expenses = sum(item[‘amount’] for item in tracker [‘expenses’])

return total_income – total_expenses

Stage 4 – Expense Categories

Allow users to categorize expenses into different categories and provide category-wise expense
reports.

def add_expense_with_category(tracker, amount, description, category):

tracker[‘expenses’].append({‘amount’: amount, ‘description’: description, ‘category’:


category})

def get_expense_by_category(tracker):

expenses_by_category = {}

for expense in tracker[‘expenses’]:

category = expense.get(‘category’, ‘Uncategorized’)

expenses_by_category.setdefault(category, []).append(expense)

return expenses_by_category

Stage 5 – Documentation and Testing

Create comprehensive documentation for the functions, including usage examples and
explanations of each stage. Test the functions with various inputs and record the outputs.
# Example usage:

Tracker = initialize_tracker()

add_income(tracker, 5000, “Salary”)

add_income(tracker, 200, “Bonus”)

add_expense(tracker, 1200, “Rent”)

add_expense_with_category(tracker, 150, “Groceries”, “Food”)

add_expense_with_category(tracker, 50, “Internet”, “Utilities”)

# Displaying the results with improved formatting

print(“********** Personal Finance Tracker **********”)

print(“Current Balance: ${:.2f}”.format(calculate_balance(tracker)))

print(“\nIncome:”)

for income_entry in tracker[‘income’]:

print(“- {} (${:.2f})”.format(income_entry[‘description’], income_entry[‘amount’]))

print(“\nExpenses by Category:”)

expenses_by_category = get_expense_by_category(tracker)

for category, expenses in expenses_by_category.items():

print(“-Category: {}”.format(category))

for expense in expenses:

print(“ –{}(${:.2f})”.format(expense[‘description’], expense[‘amount’]))


Below the entire program with its respective output:
def initialize_tracker():

return {'income': [], 'expenses': []}

def add_income(tracker, amount, description):

tracker['income'].append({'amount': amount, 'description': description})

def add_expense(tracker, amount, description):

tracker['expenses'].append({'amount': amount, 'description': description})

def calculate_balance(tracker):

total_income = sum(item['amount'] for item in tracker['income'])

total_expenses = sum(item['amount'] for item in tracker['expenses'])

return total_income - total_expenses

def add_expense_with_category(tracker, amount, description, category):

tracker['expenses'].append({'amount': amount, 'description': description,


'category': category})

def get_expense_by_category(tracker):

expenses_by_category = {}

for expense in tracker['expenses']:

category = expense.get('category', 'Uncategorized')

expenses_by_category.setdefault(category, []).append(expense)

return expenses_by_category

# Example usage:
tracker = initialize_tracker()
add_income(tracker, 5000, "Salary")
add_income(tracker, 200, "Bonus")
add_expense(tracker, 1200, "Rent")
add_expense_with_category(tracker, 150, "Groceries", "Food")
add_expense_with_category(tracker, 50, "Internet", "Utilities")

# Displaying the results with improved formatting


print("********** Personal Finance Tracker **********")
print("Current Balance: ${:.2f}".format(calculate_balance(tracker)))

print("\nIncome:")
for income_entry in tracker['income']:
print("- {} (${:.2f})".format(income_entry['description'],
income_entry['amount']))

print("\nExpenses by Category:")
expenses_by_category = get_expense_by_category(tracker)
for category, expenses in expenses_by_category.items():
print("- Category: {}".format(category))
for expense in expenses:
print(" - {} (${:.2f})".format(expense['description'], expense['amount']))

Output:

Reference

Downey,A. (2015). Think Python: How to think like a computer scientist, 2nd Edition.

You might also like