Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to calculate BMI and categorize - Python Program

Example 1 :

def bmi(weight, height): """Calculate BMI and return category.""" value = weight / (height ** 2) if value < 18.5: category = "Underweight" elif value < 24.9: category = "Normal" elif value < 29.9: category = "Overweight" else: category = "Obese" return value, category bmi_value, category = bmi(70, 1.75) print("BMI:", round(bmi_value, 2), category)

Output

 
OUTPUT  :
BMI: 22.86 Normal 
 

Example 2 : Advanced Program

def calculate_bmi_and_categorize(weight_kg, height_m): """ Calculates BMI and categorizes it based on standard classifications. Args: weight_kg (float): Weight in kilograms. height_m (float): Height in meters. Returns: tuple: A tuple containing the calculated BMI (float) and its category (str). Returns (None, "Invalid input") if height_m is zero or negative. """ if height_m <= 0: return None, "Invalid input: Height must be a positive value." bmi = weight_kg / (height_m ** 2) if bmi < 18.5: category = "Underweight" elif 18.5 <= bmi < 24.9: category = "Normal weight" elif 24.9 <= bmi < 29.9: category = "Overweight" else: category = "Obese" return bmi, category # Example Usage: weight = int(input("Enter Weight in Kilograms (kg) : ")) # kilograms height = float(input("Enter Height in Metres (m) : ")) # meters bmi_value, bmi_category = calculate_bmi_and_categorize(weight, height) if bmi_value is not None: print(f"For a weight of {weight} kg and height of {height} m:") print(f"Your BMI is: {bmi_value:.2f}") print(f"Category: {bmi_category}") else: print(bmi_category) # Another example: weight_invalid = 60 height_invalid = 0 bmi_value_invalid, bmi_category_invalid = calculate_bmi_and_categorize(weight_invalid, height_invalid) print(bmi_category_invalid)

Output

 
OUTPUT  :
Enter Weight in Kilograms (kg) : 75
Enter Height in Metres (m) : 1.75
For a weight of 75 kg and height of 1.75 m:
Your BMI is: 24.49
Category: Normal weight
Invalid input: Height must be a positive value.

Explanation:

The calculate_bmi_and_categorize function takes two arguments: weight_kg (in kilograms) and height_m (in meters).

Input Validation:

It first checks if height_m is valid (greater than zero) to prevent division by zero or negative values, returning an "Invalid input" message if necessary.

BMI Calculation:

It calculates the BMI using the formula: BMI = weight / (height^2).

Categorization:

It then categorizes the calculated BMI into one of the following standard classifications: "Underweight", "Normal weight", "Overweight", or "Obese" using a series of if-elif-else statements.

Return Value:

The function returns a tuple containing the calculated bmi and its corresponding category.