BMI Calculator Python


In this short tutorial, we will create a BMI calculator in Python. It will take the height and weight of a person and calculate their BMI.

BMI stands for Body Mass Index. It is a measure of body fat.

The BMI is used to determine a person's body status and health. A range of BMI values is associated with different health statuses.

BMI Range Status
Below 18.5 Underweight
18.5 - 25 Normal
25 - 30 Overweight
30 and above Obese

The body mass index is calculated by taking the weight in kilograms and dividing it by the square of the height in meters. i.e weight / (height * height).

BMI calculator Python

    Table Of Contents

  1. Creating BMI Calculator in Python
  2. Finding Bugs in BMI Calculator
  3. Complete Code for Python BMI Calculator

Creating BMI Calculator in Python

We will create this BMI calculator step by step. First, we will go forward with a simple approach and then we will look at possible bugs that may arise in the code and then modify the code to fix the bugs.

Every step will have a heading for a better understanding of the code.

I. Create a file for the BMI calculator.

Use your favorite code editor to create a file called bmi-calculator.py. We will use this file to write code for the BMI calculator.

II. Take Input From The User

First, we will take height and weight input from the user. We will use the input() function to take input from the user and store it in a variable.

The input Python function takes a string as an argument. The string is what the user will see when he/she will enter the input. The string can be anything like Enter your height in meters or Enter your weight in kilograms.

The input function will return the input as a string. So we will convert the string to float or integer using the float() or int() function.

# take input from user
height = float(input("Enter your height in centimeters: "))
weight = float(input("Enter your weight in kilograms: "))

III. Calculate BMI

Now we will calculate the BMI. Using the formula weight / (height * height).

Make sure the unit of the height is in meters and the unit of the weight is in kilograms.

Our height is in centimeters so first, divide it by 100 to get the height in meters.

Now calculate the BMI using the formula and store it in a variable called bmi.

# convert height to meters
height = height / 100

# calculate BMI
bmi = weight / (height * height)

IV. Display User's BMI and Status

See the table above to know what BMI value is associated with what status. Now we will display the BMI and status to the user.

We will use the if statement to check the BMI value. If the BMI value is less than 18.5, then we will display the status as Underweight. And will do so on for every other condition using the elif statement.

# print bmi and category
if bmi < 18.5:
    print(f"Your BMI is {bmi:.2f} and you are underweight.")
elif bmi < 25:
    print(f"Your BMI is {bmi:.2f} and you are normal.")
elif bmi < 30:
    print(f"Your BMI is {bmi:.2f} and you are overweight.")
else:
    print(f"Your BMI is {bmi:.2f} and you are obese.")

So we have created a BMI calculator in Python. Now we will look at possible bugs that may arise in the code and fix it.


Finding Bugs in BMI Calculator

The above BMI calculator is created with a very simple approach without thinking about situations it may fail in.

I. Wrong Input Fixing

The first problem may arise when the user inputs any random string instead of a number. For example, if the user enters "hello" instead of "5.5", then the program will not be able to convert the string to float and will throw an error.

wrong input BMI calculator Python
Wrong Input BMI Calculator

To solve this problem, we will use the try and except statements and convert the string to float within the try block. If the string is not a number, then the except block will be executed and the program will throw an error.

# take input from user
height = input("Enter your height in centimeters: ")
weight = input("Enter your weight in kilograms: ")

# convert input from string to float
try:
    height = float(height)
    weight = float(weight)
except ValueError:
    print("Invalid input. Please input numbers.\n")
    exit()

II. Negative or Zero Input Fixing

Now we are sure that input will always be a number. The second problem may arise when a user enters a negative number or Zero.

We know neither the height nor the weight can be negative or zero. So we will check if the height or weight is negative or zero. If it is, then we will display an error message and exit the program.

# check if height and weight are positive
if height <= 0 or weight <= 0:
    print("Negative numbers are not allowed.\n")
    exit()

III. Execute Program Until Find BMI

Now all the bugs are solved but our program keeps closing when the user inputs the wrong input and we have to execute the program again because we use the exit() function to exit the program.

To solve this problem, we will use a loop to execute the program until the user inputs the correct input.

Here is what we will do:

while True:
    height = input("Enter your height in centimeters: ")
    weight = input("Enter your weight in kilograms: ")

    # check if height and weight can be converted to float
    try:
        height = float(height)
        weight = float(weight)
    except ValueError:
        print("Invalid input. Please input numbers.\n")
        # continue to ask for input
        continue

    # check if height and weight are positive
    if height <= 0 or weight <= 0:
        print("Negative numbers are not allowed.\n")
        # continue to ask for input
        continue
    else:
        break

Now the program will keep asking for input until the user inputs the correct input.


Complete Code for Python BMI Calculator

Here is the complete code for the BMI calculator in Python.

# bmi calculator
while True:
    height = input("Enter your height in centimeters: ")
    weight = input("Enter your weight in kilograms: ")

    # check if height and weight can be converted to float
    try:
        height = float(height)
        weight = float(weight)
    except ValueError:
        print("Invalid input. Please input numbers.\n")
        # continue to ask for input
        continue

    # check if height and weight are positive
    if height <= 0 or weight <= 0:
        print("Negative numbers are not allowed.\n")
        # continue to ask for input
        continue
    else:
        break

# conver height to meters
height = height / 100

# calculate bmi
bmi = weight / (height ** 2)

# print bmi and category
if bmi < 18.5:
    print(f"Your BMI is {bmi:.2f} and you are underweight.")
elif bmi < 25:
    print(f"Your BMI is {bmi:.2f} and you are normal.")
elif bmi < 30:
    print(f"Your BMI is {bmi:.2f} and you are overweight.")
else:
    print(f"Your BMI is {bmi:.2f} and you are obese.")

Here is an example output of the program.

output BMI calculator Python
Output Example Of BMI Calculator

Conclusion

In this article, we have created a bug-free BMI calculator in Python. We have used the following concepts:

Happy Coding! 😇