Exercise: Conditionals

Create a program to calculate the BMI (body mass index) of a person. Ask the user for his height in meters and his weight in kg. 

Formula:

  • BMI = weight / (height * height)
  • Weight in Kg
  • Height in Meters 

In case you want to use feet and inches for the height and pounds for the weight, you can use the following formula:

BMI = (weight / (height * height)) * 703

  • Weight in Pounds
  • Height in inches
  • 1 foot = 12 inches

Print the BMI and the classification according to the following table.







Goodluck. Do the exercise and when you're done come back here to see the solution.


SOLUTION:

Let's start by asking for the height and weight of the person. I am going to use meters  and kilograms.

print("This program calculates your body mass index")

weight = float ( input("Type your weight in Kg (ex. 70.5): ") )
height = float ( input("Type your weight in Meters (ex. 1.70): ") )

bmi = weight / (height ** 2)

print("Your BMI is: ",round(bmi,2))

if (bmi <=18.5):
    classification= "Underweight"
elif(bmi > 18.5 and bmi <= 24.9):
     classification= "Normal weight"
elif(bmi > 24.9 and bmi <= 29.9):
     classification= "Overweight"
else:
    classification = "Obesity"

print("The classification of your BMI  is:", classification)
    

This is how our code will look like.

Using 70 kilos as weight and height 1.70 meters, let's run it to see if it's working:

== RESTART: C:/Users/ameny/OneDrive/Desktop/Python Revision/bmi_exercise.py ==
This program calculates your body mass index
Type your weight in Kg (ex. 70.5): 70
Type your weight in Meters (ex. 1.70): 1.70
Your BMI is:  24.22
The classification of your BMI  is: Normal weight
>>> 

And it's working. Our bmi is 24.2 and the classification is normal weight. You can try out different values to see the bmi classification. I hope you enjoyed doing this exercise? If you have any question just leave it in the comment section. 

I will see you in our next tutorial.





No comments:

Post a Comment

Python Programming Tutorial 15

 Error Handling Anytime we work with user input, we should make sure not only the data is valid and within the range we want, like what we d...