0% found this document useful (0 votes)
20 views19 pages

Module Code

These are some instructions that could be useful to someone with an IT career

Uploaded by

puriemwangi8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views19 pages

Module Code

These are some instructions that could be useful to someone with an IT career

Uploaded by

puriemwangi8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Module Code:

Module Title:
Name of Class/Group:
Assignment Title:
Student ID Number:
Date of Submission:

I confirm that this assignment is my own work.


Where I have referred to academic sources, I have provided in-text citations and included the
sources in the final reference list.

1
Table of Contents
Title......................................................................................................................................................3
1. Analysis............................................................................................................................................4
2. Design- Algorithms...........................................................................................................................4
2.1 User Login..................................................................................................................................4
2.2 Main Menu Navigation................................................................................................................5
2.3 View Progress Summary............................................................................................................7
3. Technical Overview..........................................................................................................................7
3.1 Table 1: Functional Breakdown and Python Techniques...........................................................8
3.2 Table Two: File Storage Design and Use Purpose....................................................................9
4. Coded Solution................................................................................................................................9
4.1 Python Code Functionality (word written)...................................................................................9
4.2. Python Code Working (Screenshot)........................................................................................15
5. Testing...........................................................................................................................................15
6. Evaluation......................................................................................................................................17
References.........................................................................................................................................19

2
Title: Health and Fitness
Tracker

3
1. Analysis
Many people are experiencing challenges in keeping their fitness progress and nutrition intake due
to busy and fixed schedules, and most importantly lack of tools and resources for that (Suresh and
Vinayakan, 2024). In as much as movable apps are known to exist, they are overwhelming and not
effective to people with low-tech skills. A simple console based Python application offers
manageable and customizable solution as python is used widely for prototype and command-line
tools due to its readability and accessibility (Pillai, 2017). This app denoted by Health and Fitness
Tracker will target beginners in fitness, intermediate users, experienced users and people with low
tech skills. Therefore, the app is obliged to allow users to log in securely with a user name and a
password, enable logging with physical activity type, duration, and intensity, allow input of daily
nutrition and calories intake, track and display progress of users, display visual summaries like
percentages and totals, and let users set personal plans. This project will be all about solving
challenges like managing multiple user data, loading data from .txt files, managing multiple user
data and tracking progress accurately.

The table below represents what the app will do and what will not be done:

In Scope Out of Scope


Console-based interaction Mobile or GUI Interface
Saving data to text files Cloud Storage or Database
Basic Login authentication Two factor Authentication
Nutrition and Fitness tracking Integration with fitness devices

The success criteria will be under the consideration that users can successfully log in and access
the menu, record activities and meals with ease, receive accurate fitness summaries and feel
motivated via clear visual progress indicators.

2. Design- Algorithms
This section provides the illustrations from the analysis into a representation of program’s logic,
which includes a pseudocode to design features for User Login system, Main Menu Navigation and
the View of progress summary.

2.1 User Login


START

4
Display “Enter Username”
Input: Username
Display “Enter Password”
Input: Password
If username and password match those stored, THEN
Display “ Login Successful”
GO TO Main Menu
ELSE
Display “Login Failed. Try Again.”
Restart Login
END

2.2 Main Menu Navigation


START Main Menu
Display:
1. Log Physical Activity
2. Log Nutrition & Calorie Intake
3. Set Fitness Plans
4. View Progress Summary
5. Exit program
Prompt User to Select an Option

IF choice == 1 Then Go to Log Physical Activity


START
Prompt User to enter type of activity – running, cycling, walking, meditation.
Prom User to enter duration in Minutes.
Prompt User to enter level of intensity.
Calculate estimated calories burned
Open ‘Activity_log.txt” in append mode
Write activity type, duration, intensity, and estimated calories.
Display “Activity Logged Successfully”

5
Return to Main Menu
END

ELSE IF Option == 2 Then Go to Log Nutrition Intake


START
Prompt User to enter Food name
Prompt user to enter total Calories

Open “nutritions_log.txt” in append mode


Write Food name, Calories, to file
Display “Nutrition Intake Successfully logged. Comeback to log the next meal.”
Return to Main Menu
END

ELSE IF Option == 3 Then Go to Set Fitness Plans


START
Prompt User to choose goal type:
1. Weight goal
2. Calorie burn goal
3. Step goal
Prompt user to enter target value for selected plan
Open “fitness_plans.txt” and save the selected plan type and target value
Display “Fitness Plan Saved Successfully”
Return to Main Menu
END

ELSE IF Option == 4 Then Go to View Progress Summary


START
Read all Records from “activity_log.txt”
Calculate Total Duration for all workouts

6
Calculate Average Calories Burned.
Read all records from nutrition_log.txt
Calculate Total Calories consumed
Display Marcos (calories) totals
Read all records from “fitness_plans.txt”
Compare Actual Performance to target value
Display % progress toward each plan
Return to Main Menu
END

ELSE I Option == 5 Then


Display “Thank you for using Fitness Tracker today. Stay Healthy!”

2.3 View Progress Summary


START
View Progress Summary
Read all records from “activity_log.txt”
Read all records from “nutrition_log.txt”
Read all records from “Fitness_plans.txt”
Display Progressive Summary;
1. Total Calories burned (kcal)
2. Total Calories Consumed (kcal)
3. Total Work out time (Hours and minutes)
4. % progress towards goals
Return t Main Menu
END

3. Technical Overview
This section seeks to illustrate how the Health and Fitness Tracker application is built. This app
uses python, a high-level, interpreted language widely adopted rapid development, with clear
syntax, built-in data handling functions, and file I/O capabilities (José, 2021). Therefore, python
helps this project via enabling modular program design through the use of procedural programming

7
principles where each function like login and setting fitness plans among others performs a specific
well defied task (Ekmekci et al. 2016). The solution employs basic data structures using “.txt” files
which Lee (2015) explains them to be suitable for lightweight and local applications and align the
project’s scope to avoid data base and cloud systems. The following tables clearly demonstrate the
logic and architecture behind implementation covering core functionalities and python techniques
used alongside file storage approach, with justifications.

3.1 Table 1: Functional Breakdown and Python Techniques


Functionality Data Structures/ Python Techniques Rationale
Storage
User Login System users.txt- Text file Open(), .readlines() .s A simple-text based
plit(), conditional if authentication
appropriate for
console apps; no need
for database
complexity.
Menu Navigation N/A for inputs only While loops, Inputs(), Permits the user to
print(), if-elif repeatedly access app
features until exit;
basic input/output flow
supports low-tech user
skills (REF).
Log Physical Activity activity_log.txt append(), .write() This maintains daily
string formatting logs, through the
structured storage of
activity type, duration,
intensity and calories
burned.
Log Nutrition and nutrition_log.txt append(), .write(), .for Supports the input of
Calories intake mat () calories and nutrients
log entries.
Set Fitness Plans fitness_plans.txt File writing and Input Enables goal setting
handling per user (e.g. step
count weight loss).
Simple storage
models supporting
personalized progress
Progress Summary All .txt files read(), Math Uses data from logs to
View operations, progress carry out
calculations computations of totals
and achievement
percentages, while
helping motivate users
with feedback.

8
3.2 Table Two: File Storage Design and Use Purpose
File Name Purpose Data Stored (structure) Rationale for file
usage
users.txt Stores Username, password per line Lightweight user
usernames authentication for
and console apps.
passwords
activity_log.txt Log date, activity type, duration, intensity, Tracks fitness data
physical calories_burned per line for analysis, history
activities and future references
nutrition_log.txt Log food, date,food,calories, per line Tracks the dietary
calories and intake of a user to
nutrition evaluate healthy
intake feeding and fitness
planning.
fitness_plans.txt Store goal_type, target_value, date_set Via comparison of
fitness actual vs planned
plans goals, helps measure
progress
progress_data.tx Cache or total_calories_burned, total_steps, Generate summaries
t store %_goals_achieved reducing repeated
performanc computation,
e enhancing after
summaries loading and graphical
analysis later

4. Coded Solution
Below is a representation of a coded solution for the health and Fitness Tracker application. The
section below will represent each function as modular and will explain via inline comments the
purpose and logic behind key operations – painted in yellow colour. This is to align with the pseudo
code in section 2, and the technical design in section 3.

4.1 Python Code Functionality (word written)


# Health and Fitness Tracker
# This has been developed in Python for a text based fitness application
1. File Paths
# This code show where data is stored locally for users in the application
import datetime
USER_FILE = "user_credentials.txt"
ACTIVITY_FILE = "activity_log.txt"
NUTRITION_FILE = "nutrition_log.txt"
PLAN_FILE = "fitness_plans.txt"

9
PROGRESS_FILE = "progress_data.txt"
2. User authentication
#The following code represent predefined user credentials for simple logins
users_db = {
"john_doe": "password123",
"mary_smith": "mypassword",
"tom_jones": "fitness2025"
}
# The function of the below code is to handle user’s log in
def login():
print("Welcome to the Health and Fitness Tracker!") # A welcome message
username = input("Enter your username: ") # to collect the user name
password = input("Enter your password: ") # to collect password
# Verify Credentials for the code below
if username in users_db:
if users_db[username] == password:
print(f"Login successful! Welcome back, {username}!") #This is for a successful login
return username
else:
print("Incorrect password. Please try again.") #this is for a wrong password
return None
else:
print("Username not found. Please try again.") # This is for an unknown user
return None
3. Navigation of the Menu
# Code below displays the main application menu and redirects for features
def main_menu(username):
print("\n--- Main Menu ---")
print("1. Log Physical Activities")
print("2. Track Nutrition and Calories")
print("3. View Progress Towards Fitness Goals")
print("4. Set a Personalized Fitness Plan")
print("5. Update Progress (Calories Burned / Workouts Completed)")
print("6. Exit")

10
choice = input("Please choose an option (1-6): ") #this is to get the user’s choice
# The following code represent redirect commands based on menu choice
if choice == "1":
log_activity(username)
elif choice == "2":
track_nutrition(username)
elif choice == "3":
view_progress(username)
elif choice == "4":
set_fitness_plan(username)
elif choice == "5":
update_progress(username)
elif choice == "6":
print("Goodbye!")
exit()
else:
print("Invalid choice. Please try again.")
main_menu(username)
4. Physical Activity logging
# Logs and keeps record of physical user activity into a file
def log_activity(username):
print("\nLogging Physical Activity...")
activity = input("Enter activity type (e.g., running, cycling): ")
duration = input("Enter duration in minutes: ")
intensity = input("Enter intensity (low, medium, high): ")
save_activity_log(username, activity, duration, intensity)
# The code below represents how activity data is saved with date in activity_log.txt
def save_activity_log(username, activity, duration, intensity):
with open(ACTIVITY_FILE, "a") as file:
date = datetime.datetime.now().strftime("%Y-%m-%d")
file.write(f"{date}, {username}, {activity}, {duration} mins, {intensity}\n")
print("Activity log saved successfully!")
5. Nutrition Logging
# This code section logs user’s calories intake
def track_nutrition(username):

11
print("\nTracking Nutrition and Calories...")
food_item = input("Enter food item: ")
calories = input("Enter calories consumed: ")
save_nutrition_log(username, food_item, calories)
# below is a code enabling nutrition data to be saved with date
def save_nutrition_log(username, food_item, calories):
with open(NUTRITION_FILE, "a") as file:
date = datetime.datetime.now().strftime("%Y-%m-%d")
file.write(f"{date}, {username}, {food_item}, {calories} kcal\n")
print("Nutrition log saved successfully!")
6. Fitness plan setup
# This allows the user to set a plan/goal and save it.
def set_fitness_plan(username):
print("\nSetting Personalized Fitness Plan...")
goal = input("Enter your fitness goal (e.g., weight loss, muscle gain): ")
save_fitness_plan(username, goal)
print(f"Your personalized fitness plan is set with the goal: {goal}")

def save_fitness_plan(username, goal):


with open(PLAN_FILE, "a") as file:
file.write(f"{username}: {goal}\n")
print("Fitness plan saved successfully!")

7. Progress Tracking
# This section of code enables the viewing of progress in comparison to the set goal.
def view_progress(username):
print("\nViewing Progress Towards Fitness Goals...")
goal = input("Enter your fitness goal (e.g., weight loss, muscle gain): ")
progress = load_progress(username)
# Below stands a series of example calculations that would be ran by the application to provide
averages in percentage
if goal.lower() == "weight loss":
calories_burned = progress.get("calories_burned", 0)
goal_calories = 3000
progress_percentage = (calories_burned / goal_calories) * 100

12
print(f"Progress towards {goal}: {progress_percentage:.2f}%")
# for instance if calories burned was 600 kcal, then the calculations will be (600/3000) * 100. This
provides 20% as the progress perecentage.
elif goal.lower() == "muscle gain":
workouts_completed = progress.get("workouts_completed", 0)
goal_workouts = 20
progress_percentage = (workouts_completed / goal_workouts) * 100
print(f"Progress towards {goal}: {progress_percentage:.2f}%")
else:
print("No progress data available for this goal.")
# For the existing progress, the code below enables reading and viewing of it.
def load_progress(username):
progress_data = {"calories_burned": 0, "workouts_completed": 0}
try:
with open(PROGRESS_FILE, "r") as file:
lines = file.readlines()
for line in lines:
if username in line:
parts = line.strip().split(", ")
for part in parts:
key, value = part.split(": ")
if key in progress_data:
progress_data[key] = int(value)
except FileNotFoundError:
print("No progress data found.")
return progress_data

8. Update progress
# The code below helps update data (calories/workouts)
def update_progress(username):
print("\nUpdate Your Progress")
progress_type = input("What progress do you want to update? (calories_burned or
workouts_completed): ").lower()
if progress_type not in ["calories_burned", "workouts_completed"]:
print("Invalid progress type.")

13
return

value = input(f"Enter the number of {progress_type.replace('_', ' ')} to update: ")


try:
value = int(value)
update_progress_data(username, progress_type, value)
except ValueError:
print("Invalid value entered. Please enter a number.")

The code below updates progress to the file


def update_progress_data(username, progress_type, value):
progress_data = load_progress(username)
if progress_type == "calories_burned":
progress_data["calories_burned"] += value
elif progress_type == "workouts_completed":
progress_data["workouts_completed"] += value

with open(PROGRESS_FILE, "a") as file:


file.write(f"{username}: calories_burned: {progress_data['calories_burned']},
workouts_completed: {progress_data['workouts_completed']}\n")
print(f"Progress updated for {username}: {progress_type} = {value}")

9. Below is the entry point


def main():
user = None()
while user is None:
user = login()
if user is None:
print(“Login failed. Please try again. \n") This is as a result of a wrong password or username

If we reach here then log in is successfull while True:


main_menu(user)

if __name__ == "__main__":
main()

14
4.2. Python Code Working (Screenshot)

5. Testing
Function Input (s) Expected Actual Pass/fail Comment
Tested Output Output
Login Username: “Login “Login Pass Test approved
john_doe Successful! Successful! hard coded
Password: Welcome back Welcome user
Password123 john_doe!” back authentication
john_doe!”

Invalid login Fake “Username not “Username Pass User rejection


Username found” or Invalid not found” or path tested
and/ password Password” Invalid
Password”

Log Activity: Entry saved in Active log Pass Confirmed entry


Activity, Running, activity_log.txt saved added in file
Nutrition, Duration:30 successfully
Intensity: high

15
View Goal: weight Show O progress Displayed Pass Dummy value
Progress loss, since “John_doe” correct goal =5000
(Calories) calories has not recorded percentage
burned: 2000 any

Set Fitness Goal: muscle Entry saved in File updated pass Has followed
Plan gain fitness_plans.txt and user specific
confirmation format
shown

16
Invalid Input: 9 “invalid choice Error pass Logged goal in
Menu please try again” message user-specific
Option shown, menu format
repeated

6. Evaluation
For a basic fitness tracker application, this program meets its intended purpose demonstrating the
use of core python programming concepts. These concepts include conditionals, loops, functions,
and file I/O. Therefore, the table below represents a custom checklist based on requirements to
prove success.

Success Criteria Met?


Users can log in securely Yes
Access to interactive menu Yes
Access to all log activities Yes
Receive of fitness summaries Yes
Support for low tech users Mostly

The strengths of the program lie of its modular design which Girithath (2016) explains to be each
function being separate and reusable, hence confirming the program’s best practices. Additionally,

17
the program has file storage to store persistent data (.txt files) which is readable by human and
computer as well. Realistic Goal tracking is also an advantage where predefined thresholds
compare burned calories and workouts to show progress. Testing of verified outcomes has also
been successful where all tested scenarios like valid/invalid logins, logs, menu and calculation of
the program are testable.

Nevertheless, the program faces challenges on no architecture for user registration unless via
server admin, no data validation for calories and also data redundancy which might manifest vie the
appendage to progress data risking conflicting records per user unless overwritten. With a few
adjustment this program can become a perfect personal fitness assistant.

18
References
Ekmekci, B., McAnany, C.E. and Mura, C., 2016. An introduction to programming for bioscientists: a
Python-based primer. PLoS computational biology, 12(6), p.e1004867.
https://journals.plos.org/ploscompbiol/article/file?id=10.1371/journal.pcbi.1004867&type=printabl
e

Giridhar, C., 2016. Learning python design patterns. Packt Publishing Ltd.
http://103.203.175.90:81/fdScript/RootOfEBooks/E%20Book%20collection%20-%202024%20-
%20G/CSE%20%20IT%20AIDS%20ML/Learning%20Python%20Design%20Patterns,
%20Second%20Edition.pdf

José, U., 2021. Python programming for data analysis. Springer Nature.
https://elib.vku.udn.vn/bitstream/123456789/2468/1/2021.%20Python%20Programming%20for
%20Data%20Analysis.pdf

Lee, K.D. and Hubbard, S., 2015. Data structures and algorithms with python (Vol. 363).
Berlin/Heidelberg, Germany: Springer.
https://eprints.ukh.ac.id/id/eprint/187/1/2015_Book_DataStructuresAndAlgorithmsWit.pdf

Pillai, A.B., 2017. Software architecture with Python. Packt Publishing Ltd.
https://www.academia.edu/download/63274164/software-architecture-python20200511-14970-
s9e5nw.pdf

Suresh Kumar, M. and Vinayakan, K., 2024. Building a sustainable fitness routine: Balancing
exercise, rest, and nutrition. International Journal of Interdisciplinary Research in Arts and
Humanities, 9(2), pp.164–169.
https://www.researchgate.net/profile/Kasi-Vinayakan/publication/387603572_BUILDING_A_SUS
TAINABLE_FITNESS_ROUTINE_BALANCING_EXERCISE_REST_AND_NUTRITION/links/
67756b0a894c55208538f163/BUILDING-A-SUSTAINABLE-FITNESS-ROUTINE-BALANCING-
EXERCISE-REST-AND-NUTRITION.pdf

19

You might also like