This Python script allows users to record their weight in pounds, automatically converting it to kilograms, and tracks entries over time with timestamps. It also enables users to look up past weights by date, showing changes from previous entries, and stores all data persistently in a JSON file for long-term tracking.
Click to view script…
import json
import os
from datetime import datetime
def lbs_to_kg(lbs):
"""Convert weight from pounds to kilograms."""
return lbs * 0.453592
def validate_date(date_str):
"""Validate date input and return a date object if valid."""
try:
return datetime.strptime(date_str, "%Y-%m-%d").date()
except ValueError:
return None
# Load existing entries from the JSON file
if os.path.exists("weight_log.json"):
with open("weight_log.json", "r") as f:
entries = json.load(f)
else:
entries = []
# Ask the user what they want to do
action = input("Do you want to (1) record a new weight or (2) look up a past weight? Enter 1 or 2: ").strip()
if action == "1":
# Record a new weight
while True:
try:
weight = float(input("Enter your weight in pounds: "))
break
except ValueError:
print("Invalid input. Please enter a number.")
now = datetime.now()
date_str = now.strftime("%Y-%m-%d")
time_str = now.strftime("%H:%M:%S")
if len(entries) > 0:
previous_weight = entries[-1]["weight_lbs"]
diff = weight - previous_weight
else:
diff = None
new_entry = {"date": date_str, "time": time_str, "weight_lbs": weight}
entries.append(new_entry)
with open("weight_log.json", "w") as f:
json.dump(entries, f, indent=4)
print(f"Weight recorded: {weight:.2f} lbs ({lbs_to_kg(weight):.2f} kg)")
if diff is not None:
if diff > 0:
print(f"You gained {diff:.2f} lbs ({lbs_to_kg(diff):.2f} kg) since the last entry.")
elif diff < 0:
print(f"You lost {-diff:.2f} lbs ({-lbs_to_kg(diff):.2f} kg) since the last entry.")
else:
print("No change in weight since the last entry.")
else:
print("This is your first entry. No previous data to compare.")
elif action == "2":
# Look up a past weight
if not entries:
print("No weight entries found. Please record a weight first.")
else:
while True:
date_input = input("Enter the date to look up (YYYY-MM-DD): ")
lookup_date = validate_date(date_input)
if lookup_date:
break
else:
print("Invalid date format. Please enter the date in YYYY-MM-DD format.")
# Find entries for the specified date
matching_entries = [entry for entry in entries if entry["date"] == date_input]
if matching_entries:
print(f"\nWeight entries for {date_input}:")
for entry in matching_entries:
weight = entry["weight_lbs"]
time = entry["time"]
print(f"- {time}: {weight:.2f} lbs ({lbs_to_kg(weight):.2f} kg)")
else:
print(f"No weight entries found for {date_input}.")
else:
print("Invalid choice. Please run the script again and enter 1 or 2.")