Ramadhan Python Challenge — Day 29


To push me to remember Python in Ramadhan 2024, then I will try to put one post per day. Btw, this is the last day of Ramadan 2024 and also the last post for the Ramadan Python Challenge. I will try to do the same thing for other events calendars and will try for other Python challenges.

Question
Create a simple program to calculate Crude Mortality Rate (CMR)

Answer

def calculate_cmr(deaths, population, multiplier=1000):
    """
    Calculate Crude Mortality Rate (CMR).
    deaths: Number of deaths.
    population: Average population for the time period.
    multiplier: Multiplier to adjust the rate (default is 1000).
    """
    if population == 0:
        return "Cannot calculate CMR. Population cannot be zero."
    
    cmr = (deaths / population) * multiplier
    return cmr

def main():
    print("Crude Mortality Rate (CMR) Calculator")
    try:
        deaths = int(input("Enter number of deaths: "))
        population = int(input("Enter average population for the time period: "))
    except ValueError:
        print("Invalid input. Please enter a whole number.")
        return
    
    cmr = calculate_cmr(deaths, population)
    if isinstance(cmr, str):
        print(cmr)
    else:
        print("Crude Mortality Rate (CMR): {:.2f}".format(cmr))

if __name__ == "__main__":
    main()

Explanation

The Crude Mortality Rate (CMR) is calculated as the number of deaths occurring in a given population during a specified time period, divided by the average population for that period, and then multiplied by a constant (usually 1000 or 100,000) to make the rate more understandable.

Here’s how the script works:

  1. It defines a calculate_cmr function that takes the number of deaths, the average population for the time period, and an optional multiplier parameter (default is 1000).
  2. Inside this function, it checks if the population is 0 (denominator is 0) and returns an error message in such cases.
  3. If there is a population, it calculates the CMR as (deaths/population) * multiplier.
  4. The main function prompts the user to enter the number of deaths and the average population for the time period.
  5. It then calls calculate_cmr with the provided numbers and prints the CMR.

You can run this script in your Python environment, enter the number of deaths and the average population for the time period when prompted, and it will calculate and display the Crude Mortality Rate (CMR). By default, it will multiply the result by 1000 to express the rate per 1000 people, but you can change the multiplier parameter if you prefer a different scale (e.g., 100,000 for a rate per 100,000 people).