BMI Calculator – Python Source Code

  • Code
  • Code With GUI
Python
# Function To Calculate BMI
def BMI_Calculator():
    try:
        # User input for height in centimeters
        height = int(input("What Is Your Height In Centimeter")) 
        # User input for weight in kilograms
        weight = int(input("What Is Your Weight In KG")) 

        # Calculating BMI using the formula
        BMI = weight/(height/100)**2 

        # Formatting BMI to two decimal places
        BMI_Format = "{:.2f}".format(BMI)

        # Categorizing BMI and providing corresponding output
        if (BMI <= 18.4):
            print(f"BMI is {BMI_Format}\n Underweight")

        elif (BMI <= 24.9):
            print(f"BMI is {BMI_Format}\n Normal weight")

        elif (BMI <= 29.9):
            print(f"BMI is {BMI_Format}\n Overweight")

        else :
            print(f"BMI is {BMI_Format}\n Obesity")

    except:
        print("Invalid input. Please enter a valid number for height and weight.")
        
# Calling the BMI Calculator function
BMI_Calculator()

# BMI Calculator Source Code - By Codotix
Python
# Importing turtle module
import turtle as te

# Function to calculate BMI 
def BMICalculator():
    # User input for height in centimeters
    height = te.numinput("BMI Calculator", "What Is Your Height In Centimeter")
    # User input for weight in kilograms
    weight = te.numinput("BMI Calculator", "What Is Your Weight In KG")

    # Calculating BMI using the formula
    BMI = weight/(height/100)**2

    # Formatting BMI to two decimal places
    BMI_Format = "{:.2f}".format(BMI)

    # Creating a Turtle screen
    screen = te.Screen()

    # Setting up the screen dimensions
    screen.setup(width=800, height=300)

    # Creating a Turtle object for drawing
    tur = te.Turtle()

    # Categorizing BMI and providing corresponding output
    if (BMI <= 18.4):
        tur.color("Yellow")
        tur.write(f"BMI is {BMI_Format}\n Underweight", align="center", font=("Arial", 20, "bold"))

    elif (BMI <= 24.9):
        tur.color("Green")
        tur.write(f"BMI is {BMI_Format}\n Normal weight", align="center", font=("Arial", 20, "bold"))

    elif (BMI <= 29.9):
        tur.color("Orange")
        tur.write(f"BMI is {BMI_Format}\n Overweight", align="center", font=("Arial", 20, "bold"))

    else :
        tur.color("Red")
        tur.write(f"BMI is {BMI_Format}\n Obesity", align="center", font=("Arial", 20, "bold"))

    # Hide the turtle after drawing
    tur.hideturtle()

    # Start the event loop for the Turtle screen
    te.mainloop()

# Calling the BMI calculator function
BMICalculator()

# BMI Calculator Source Code - By Codotix

Leave a Comment

Your email address will not be published. Required fields are marked *