import csv
import os
from datetime import datetime
class InterheartRiskCalculator:
def __init__(self):
self.csv_filename = "interheart_risk_scores.csv"
self.setup_csv()
def setup_csv(self):
"""Create CSV file with headers if it doesn't exist"""
if not os.path.exists(self.csv_filename):
headers = [
'Name', 'Age', 'Gender', 'Date_Assessed', 'Age_Score', 'Smoking_Score',
'Secondhand_Smoke_Score', 'Diabetes_Score', 'High_BP_Score',
'Family_History_Score', 'Waist_Hip_Ratio_Score', 'Stress_Score',
'Depression_Score', 'Salty_Food_Score', 'Fried_Food_Score',
'Fruit_Score', 'Vegetable_Score', 'Meat_Score', 'Physical_Activity_Score',
'Total_Score'
]
with open(self.csv_filename, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(headers)
def get_safe_input(self, prompt, valid_options=None, input_type=str):
"""Get input with error handling"""
while True:
try:
user_input = input(prompt).strip()
if input_type == int:
user_input = int(user_input)
elif input_type == float:
user_input = float(user_input)
if valid_options and user_input not in valid_options:
print(f"Invalid input. Please choose from: {valid_options}")
continue
return user_input
except ValueError:
print(f"Invalid input. Please enter a valid {input_type.__name__}.")
except KeyboardInterrupt:
print("\nExiting program...")
return None
def calculate_age_score(self, age, gender):
"""Calculate age score based on age and gender"""
if gender.lower() == 'male' and age >= 55:
return 2
elif gender.lower() == 'female' and age >= 65:
return 2
else:
return 0
def calculate_smoking_score(self):
"""Calculate smoking score"""
print("\nSmoking Status:")
print("1. Never smoked")
print("2. Former smoker (last smoked more than 12 months ago)")
print("3. Current smoker (1-5 cigarettes per day)")
print("4. Current smoker (6-10 cigarettes per day)")
print("5. Current smoker (11-15 cigarettes per day)")
print("6. Current smoker (16-20 cigarettes per day)")
print("7. Current smoker (more than 20 cigarettes per day)")
choice = self.get_safe_input("Enter your choice (1-7): ", [1, 2, 3, 4, 5, 6, 7], int)
smoking_scores = {1: 0, 2: 2, 3: 2, 4: 4, 5: 6, 6: 7, 7: 11}
return smoking_scores.get(choice, 0)
def calculate_secondhand_smoke_score(self):
"""Calculate secondhand smoke exposure score"""
print("\nSecondhand Smoke Exposure (past 12 months):")
print("1. Less than 1 hour per week or no exposure")
print("2. One or more hours per week")
choice = self.get_safe_input("Enter your choice (1-2): ", [1, 2], int)
return 0 if choice == 1 else 2
def calculate_diabetes_score(self):
"""Calculate diabetes score"""
choice = self.get_safe_input("Do you have diabetes? (y/n): ", ['y', 'n', 'yes', 'no'])
return 6 if choice.lower() in ['y', 'yes'] else 0
def calculate_high_bp_score(self):
"""Calculate high blood pressure score"""
choice = self.get_safe_input("Do you have high blood pressure? (y/n): ", ['y', 'n', 'yes', 'no'])
return 5 if choice.lower() in ['y', 'yes'] else 0
def calculate_family_history_score(self):
"""Calculate family history score"""
choice = self.get_safe_input("Have either or both of your biological parents had a heart attack? (y/n): ",
['y', 'n', 'yes', 'no'])
return 4 if choice.lower() in ['y', 'yes'] else 0
def calculate_waist_hip_ratio_score(self):
"""Calculate waist-to-hip ratio score"""
print("\nWaist-to-Hip Ratio:")
print("1. Less than 0.873")
print("2. 0.873 to 0.963")
print("3. Greater than or equal to 0.964")
choice = self.get_safe_input("Enter your choice (1-3): ", [1, 2, 3], int)
ratio_scores = {1: 0, 2: 2, 3: 4}
return ratio_scores.get(choice, 0)
def calculate_stress_score(self):
"""Calculate work/home stress score"""
print("\nWork or Home Life Stress (past year):")
print("1. Never or some periods")
print("2. Several periods of stress or permanent stress")
choice = self.get_safe_input("Enter your choice (1-2): ", [1, 2], int)
return 0 if choice == 1 else 3
def calculate_depression_score(self):
"""Calculate depression score"""
choice = self.get_safe_input("In the past 12 months, have you felt sad, blue, or depressed for two weeks or more in a row? (y/n): ",
['y', 'n', 'yes', 'no'])
return 3 if choice.lower() in ['y', 'yes'] else 0
def calculate_dietary_scores(self):
"""Calculate all dietary factor scores"""
scores = {}
# Salty food
choice = self.get_safe_input("Do you eat salty food or snacks one or more times a day? (y/n): ",
['y', 'n', 'yes', 'no'])
scores['salty'] = 1 if choice.lower() in ['y', 'yes'] else 0
# Fried food
choice = self.get_safe_input("Do you eat deep fried foods or fast foods 3 or more times a week? (y/n): ",
['y', 'n', 'yes', 'no'])
scores['fried'] = 1 if choice.lower() in ['y', 'yes'] else 0
# Fruit
choice = self.get_safe_input("Do you eat fruit one or more times daily? (y/n): ",
['y', 'n', 'yes', 'no'])
scores['fruit'] = 0 if choice.lower() in ['y', 'yes'] else 1
# Vegetables
choice = self.get_safe_input("Do you eat vegetables one or more times daily? (y/n): ",
['y', 'n', 'yes', 'no'])
scores['vegetables'] = 0 if choice.lower() in ['y', 'yes'] else 1
# Meat
choice = self.get_safe_input("Do you eat meat and/or poultry 2 or more times daily? (y/n): ",
['y', 'n', 'yes', 'no'])
scores['meat'] = 2 if choice.lower() in ['y', 'yes'] else 0
return scores
def calculate_physical_activity_score(self):
"""Calculate physical activity score"""
print("\nPhysical Activity (leisure time):")
print("1. Mainly sedentary or mild exercise (minimal effort)")
print("2. Moderate or strenuous physical activity")
choice = self.get_safe_input("Enter your choice (1-2): ", [1, 2], int)
return 2 if choice == 1 else 0
def collect_individual_data(self):
"""Collect all data for one individual"""
print("\n" + "="*50)
print("INTERHEART Risk Score Assessment")
print("="*50)
# Basic information
name = self.get_safe_input("Enter name: ")
if name is None:
return None
age = self.get_safe_input("Enter age: ", input_type=int)
if age is None:
return None
gender = self.get_safe_input("Enter gender (male/female): ", ['male', 'female'])
if gender is None:
return None
# Calculate scores
age_score = self.calculate_age_score(age, gender)
smoking_score = self.calculate_smoking_score()
secondhand_smoke_score = self.calculate_secondhand_smoke_score()
diabetes_score = self.calculate_diabetes_score()
high_bp_score = self.calculate_high_bp_score()
family_history_score = self.calculate_family_history_score()
waist_hip_ratio_score = self.calculate_waist_hip_ratio_score()
stress_score = self.calculate_stress_score()
depression_score = self.calculate_depression_score()
dietary_scores = self.calculate_dietary_scores()
physical_activity_score = self.calculate_physical_activity_score()
# Calculate total score (sum of all individual scores)
total_score = (age_score + smoking_score + secondhand_smoke_score + diabetes_score +
high_bp_score + family_history_score + waist_hip_ratio_score +
stress_score + depression_score + dietary_scores['salty'] +
dietary_scores['fried'] + dietary_scores['fruit'] +
dietary_scores['vegetables'] + dietary_scores['meat'] +
physical_activity_score)
# Show score breakdown
print(f"\n--- Score Breakdown ---")
print(f"Age: {age_score}")
print(f"Smoking: {smoking_score}")
print(f"Secondhand Smoke: {secondhand_smoke_score}")
print(f"Diabetes: {diabetes_score}")
print(f"High Blood Pressure: {high_bp_score}")
print(f"Family History: {family_history_score}")
print(f"Waist-Hip Ratio: {waist_hip_ratio_score}")
print(f"Stress: {stress_score}")
print(f"Depression: {depression_score}")
print(f"Salty Food: {dietary_scores['salty']}")
print(f"Fried Food: {dietary_scores['fried']}")
print(f"Fruit: {dietary_scores['fruit']}")
print(f"Vegetables: {dietary_scores['vegetables']}")
print(f"Meat: {dietary_scores['meat']}")
print(f"Physical Activity: {physical_activity_score}")
print(f"TOTAL SCORE: {total_score}")
# Prepare data for CSV
data = [
name, age, gender, datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
age_score, smoking_score, secondhand_smoke_score, diabetes_score,
high_bp_score, family_history_score, waist_hip_ratio_score,
stress_score, depression_score, dietary_scores['salty'],
dietary_scores['fried'], dietary_scores['fruit'],
dietary_scores['vegetables'], dietary_scores['meat'],
physical_activity_score, total_score
]
return data
def save_to_csv(self, data):
"""Save individual data to CSV file"""
try:
with open(self.csv_filename, 'a', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(data)
print(f"\nData saved successfully to {self.csv_filename}")
except Exception as e:
print(f"Error saving data: {e}")
def display_results(self, data):
"""Display individual results"""
print("\n" + "="*50)
print("ASSESSMENT RESULTS")
print("="*50)
print(f"Name: {data[0]}")
print(f"Age: {data[1]} ({data[2]})")
print(f"Total Risk Score: {data[-1]}")
# Risk interpretation based on your criteria
if data[-1] <= 9:
risk_level = "Low Risk"
risk_description = "(0-9 points)"
elif data[-1] <= 15:
risk_level = "Moderate Risk"
risk_description = "(10-15 points)"
else:
risk_level = "High Risk"
risk_description = "(16-48 points)"
print(f"Risk Level: {risk_level} {risk_description}")
print("\nNote: This is a screening tool. Please consult healthcare professionals for proper medical advice.")
def run(self):
"""Main program loop"""
print("Welcome to the INTERHEART Risk Score Calculator!")
while True:
try:
data = self.collect_individual_data()
if data is None:
break
self.display_results(data)
self.save_to_csv(data)
continue_choice = self.get_safe_input("\nDo you want to assess another individual? (y/n): ",
['y', 'n', 'yes', 'no'])
if continue_choice.lower() in ['n', 'no']:
break
except KeyboardInterrupt:
print("\nProgram interrupted by user.")
break
except Exception as e:
print(f"An error occurred: {e}")
continue
print("Thank you for using the INTERHEART Risk Score Calculator!")
# Run the program
if __name__ == "__main__":
calculator = InterheartRiskCalculator()
calculator.run()