Coding a simple Python BMI calculator using functions

LearnTips LearnTips Coding a simple Python BMI calculator using functions

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #3379

    In this tutorial, I am going to use Python 3.8.2 to code a simple Python BMI calculator. BMI is a way to assess whether your weight is in the healthy range. It is calculated as the ratio of weight in kilograms divided by height in metres squared.

    Body Mass Index (BMI) = Weight (kg) / Height (m2)

    A simple Python BMI calculator using functions

    Step 1: In your text editor, create a new file and save it with the extension .py. For this tutorial, let’s name it bmi.py.

    Step 2: Let’s add the code to receieve weight and height inputs from the user. We are going to use float() and input() Python functions to achieve this.

    #Coding a simple Python BMI calculator
    
    # Receive input from the user
    weight=float(input("Enter your weight in kilograms:"))
    height=float(input("Enter your height in centimeters:"))
    

    The input() function will simply allow the user to enter a text input. Next, the float() function will convert the entered number into a floating point number.

    Step 3: Now let’s add the formula to calculate BMI.

    # Calculate the BMI
    bmi=weight/((height/100)*(height/100))
    

    We have added a variable called bmi. In Python, variable gives data to the computer for processing. The asterisk * is used to perform multiplication and the forward slash / is used to perform division. We have divided height by 100 to convert centimeters into meters and we have multiplied height with height in order to square it. And then we have divided weight by height and stored the value in the variable bmi.

    Step 4: Let’s display the calculated BMI to the user.

    # Display the result to the user
    print("Your Body Mass Index (BMI) is:",round(bmi,2))
    

    The print command will print everything you have added inside the parentheses (brackets). The round command will round the resulting value to 2 decimal places.

    Step 5: Save the file as bmi.py. Your final code will look something like this.

    # Coding a simple Python BMI calculator
    
    # Receive input from the user
    weight=float(input("Enter your weight in kilograms:"))
    height=float(input("Enter your height in centimeters:"))
    
    # Calculate the BMI
    bmi=weight/((height/100)*(height/100))
    
    # Display the result to the user
    print("Your Body Mass Index (BMI) is:",round(bmi,2))
    

     
    Step 5: Now let’s run our Python script in the command-line interpreter.

    Enter your weight in kilograms: 67
    Enter your height in centimeters: 167
    Your Body Mass Index (BMI) is: 24.02
    

    More resources:
    Built-in functions – Python 3 documentation

Viewing 1 post (of 1 total)