Python индекс массы тела

BMI Calculator Using Python Tkinter [Complete Example]

In this Python Tkinter Tutorial, we will learn to create a BMI Calculator Using Python Tkinter.
Body Mass Index (BMI) is a simple calculation using a person’s height and weight.

BMI Calculator using Python Tkinter

The formula is BMI = kg/m2 where kg is a person’s weight in kilograms and m2 is their height in meters squared. A BMI of 25.0 or more is overweight, while the healthy range is 18.5 to 24.9.

BMI Categories:

Functions Explanation:

There can many ways to create an interface for this program but all the programs will have the same function. In this section, we will see how the main function works in this program. So there are two functions used to display the BMI result.

calculate_bmi():

  • kg = int(weight_tf.get())
    this line of code gets the user weight, convert it to integers, and then stores the value in the variable kg
  • m = int(height_tf.get())/100
    this line of code gets the user height, converts it into integers, divides the result with 100 so that centimeters become meters, and then stores it in a variable m.
  • bmi = kg/(m*m)
    this is the formula for finding BMI. We have stored the formula in a variable BMI.
  • bmi = round(bmi, 1 )
    before round off the result was appearing in multiple decimal values. But after using the round function it looks simplified & easy to read.
    without round function, the result appeared is 20.061728395061728 and after applying the round function the result appeared is 20.1.
  • bmi_index(bmi)
    We have called the bmi_index() function to compare the BMI value with the BMI categories.
def calculate_bmi(): kg = int(weight_tf.get()) m = int(height_tf.get())/100 bmi = kg/(m*m) bmi = round(bmi, 1) bmi_index(bmi)

In this function, the final result displayed depending upon the BMI value & BMI category it belongs to.

Читайте также:  Python list pop by index

BMI Categories:

def bmi_index(bmi): if bmi < 18.5: messagebox.showinfo('bmi-pythonguides', f'BMI = is Underweight') elif (bmi > 18.5) and (bmi < 24.9): messagebox.showinfo('bmi-pythonguides', f'BMI = is Normal') elif (bmi > 24.9) and (bmi < 29.9): messagebox.showinfo('bmi-pythonguides', f'BMI = is Overweight') elif (bmi > 29.9): messagebox.showinfo('bmi-pythonguides', f'BMI = is Obesity') else: messagebox.showerror('bmi-pythonguides', 'something went wrong!') 

Source Code:

Here is the complete source code of the BMI calculator. The code can be run on any version of python3 but it must have Tkinter installed on it. In case of any doubt or error please leave a comment.

from tkinter import * from tkinter import messagebox def reset_entry(): age_tf.delete(0,'end') height_tf.delete(0,'end') weight_tf.delete(0,'end') def calculate_bmi(): kg = int(weight_tf.get()) m = int(height_tf.get())/100 bmi = kg/(m*m) bmi = round(bmi, 1) bmi_index(bmi) def bmi_index(bmi): if bmi < 18.5: messagebox.showinfo('bmi-pythonguides', f'BMI = is Underweight') elif (bmi > 18.5) and (bmi < 24.9): messagebox.showinfo('bmi-pythonguides', f'BMI = is Normal') elif (bmi > 24.9) and (bmi < 29.9): messagebox.showinfo('bmi-pythonguides', f'BMI = is Overweight') elif (bmi > 29.9): messagebox.showinfo('bmi-pythonguides', f'BMI = is Obesity') else: messagebox.showerror('bmi-pythonguides', 'something went wrong!') ws = Tk() ws.title('PythonGuides') ws.geometry('400x300') ws.config(bg='#686e70') var = IntVar() frame = Frame( ws, padx=10, pady=10 ) frame.pack(expand=True) age_lb = Label( frame, text="Enter Age (2 - 120)" ) age_lb.grid(row=1, column=1) age_tf = Entry( frame, ) age_tf.grid(row=1, column=2, pady=5) gen_lb = Label( frame, text='Select Gender' ) gen_lb.grid(row=2, column=1) frame2 = Frame( frame ) frame2.grid(row=2, column=2, pady=5) male_rb = Radiobutton( frame2, text = 'Male', variable = var, value = 1 ) male_rb.pack(side=LEFT) female_rb = Radiobutton( frame2, text = 'Female', variable = var, value = 2 ) female_rb.pack(side=RIGHT) height_lb = Label( frame, text="Enter Height (cm) " ) height_lb.grid(row=3, column=1) weight_lb = Label( frame, text="Enter Weight (kg) ", ) weight_lb.grid(row=4, column=1) height_tf = Entry( frame, ) height_tf.grid(row=3, column=2, pady=5) weight_tf = Entry( frame, ) weight_tf.grid(row=4, column=2, pady=5) frame3 = Frame( frame ) frame3.grid(row=5, columnspan=3, pady=10) cal_btn = Button( frame3, text='Calculate', command=calculate_bmi ) cal_btn.pack(side=LEFT) reset_btn = Button( frame3, text='Reset', command=reset_entry ) reset_btn.pack(side=LEFT) exit_btn = Button( frame3, text='Exit', command=lambda:ws.destroy() ) exit_btn.pack(side=RIGHT) ws.mainloop()

In this output, the user needs to fill in some information like age, gender, height & weight. Out of this information height & weight is used to calculate the BMI. Then the BMI passes through conditions.

Each condition has a remark (underweight, Normal, overweight, etc). The result is displayed using a message box.

bmi calculator using python tkinter

This is how we can make a BMI Calculator using Python Tkinter.

You may like the following Python TKinter tutorials:

In this tutorial, we learned, how to BMI Calculator using Python Tkinter.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Создание калькулятора ИМТ с помощью Python

В следующем руководстве мы поймем, как создать калькулятор индекса массы тела (ИМТ) с помощью языка программирования Python. Прежде, чем приступить к его созданию, давайте кратко обсудим, что такое индекс массы тела (ИМТ).

Понимание индекса массы тела (ИМТ)

ИМТ, сокращение от индекса массы тела, является мерой относительного веса, основанной на массе и росте человека. Обычно мы используем индекс массы тела, чтобы классифицировать людей на основе их роста и веса. К этим категориям относятся недостаточный вес, здоровое состояние, избыточный вес и даже ожирение. Более того, он также принят различными странами в целях пропаганды здорового питания.

Мы можем рассматривать индекс массы тела (ИМТ) как замену прямым измерениям жира в организме. Кроме того, ИМТ – это недорогой и простой в выполнении метод проверки весовых категорий, которые могут вызвать проблемы со здоровьем.

Работа калькулятора ИМТ

Калькулятор ИМТ принимает вес и рост человека и рассчитывает индекс массы тела (ИМТ) этого человека.

Например, если рост и вес человека 155 см и 57 кг. ИМТ этого человека будет 23,73 (приблизительно), что означает, что человек здоров.

Индекс массы тела (ИМТ) – это показатель жира в организме на основе роста и веса соответственно.

На основе ИМТ человека калькулятор возвращает отчет об общем состоянии здоровья человека. В следующей таблице показано, как проводится классификация ИМТ для определения состояния здоровья человека.

ИМТ Статус веса
1 Ниже 18,5 Недостаточный вес
2 18,5 – 24,9 Обычный
3 25,0 – 29,9 Избыточный вес
4 30.0 и выше Ожирение

Теперь приступим к написанию кода проекта.

Создание калькулятора ИМТ с использованием Python

В качестве первого шага мы создадим новый программный файл Python и назовем его BMI_Calculator.py. В этом файле мы начнем с создания блока кода, чтобы узнать у пользователя его рост и вес. Это легко сделать с помощью функции input().

# asking for input from the users the_height = float(input("Enter the height in cm: ")) the_weight = float(input("Enter the weight in kg: "))

В приведенном выше фрагменте кода мы определили две переменные: the_height и the_weight, которые используют функцию input() для приема ввода от пользователя. Мы также включили функцию float() вне функции input(), чтобы преобразовать входную строку в тип данных float, чтобы мы могли выполнять с ней вычисления.

Далее мы рассчитаем индекс массы тела.

Мы будем использовать следующую формулу для расчета ИМТ.

Формула ИМТ

Давайте реализуем приведенную выше формулу в программе Python.

# defining a function for BMI the_BMI = the_weight /(the_height/100)**2

В приведенном выше фрагменте кода мы определили функцию для BMI, используя приведенную выше формулу. Мы разделили высоту на 100, чтобы перевести сантиметры в метры.

Теперь давайте напечатаем ИМТ.

# printing the BMI print("Your Body Mass Index is", the_BMI)

В приведенном выше фрагменте кода мы напечатали утверждение, в котором указан ИМТ человека.

Теперь мы напечатаем отчет о текущем состоянии здоровья пользователя на основе его ИМТ. Этот блок кода будет довольно упрощен для лучшего понимания.

Мы будем использовать условия if-elif-else для классификации.

# using the if-elif-else conditions if the_BMI 

В приведенном выше фрагменте кода мы использовали значение переменной the_BMI в операторе if-elif-else, чтобы проверить, относится ли ИМТ человека к одной из категорий.

Программа напечатает выписку на следующем основании:

  • Если ИМТ меньше или равен 18,5, то программа возвращает условие недостаточного веса.
  • Если ИМТ меньше или равен 24,9, программа возвращает условие «Здоров».
  • Если ИМТ меньше или равен 29,9, то программа возвращает условие избыточного веса.
  • Если ни одно из вышеперечисленных условий не истинно, программа возвращает условие ожирения.
    Значит, программа завершена.

Давайте посмотрим полный исходный код программы и ее вывод.

# asking for input from the users the_height = float(input("Enter the height in cm: ")) the_weight = float(input("Enter the weight in kg: ")) # defining a function for BMI the_BMI = the_weight / (the_height/100)**2 # printing the BMI print("Your Body Mass Index is", the_BMI) # using the if-elif-else conditions if the_BMI 
Enter the height in cm: 160 Enter the weight in kg: 61 Your Body Mass Index is 23.828124999999996 Awesome! You are healthy.

Источник

Решить задачу на Python.

Задача.
Напишите программу для определения индекса массы тела.

На первый взгляд, это - простая задача.
Решение не сложно написать с помощью условий
if - elif -else.
Но она является задачей повышенной трудности.
Как написать решение задачи с помощью функции ?

Формулу для расчёта индекса массы тела нужно искать в Википеди.

id2746

m = float (input('Введите ваш вес: ')) h = float (input('Введите ваш рост в см: ')) h = h/100 #переводим в метры def index(m,h): index_mass = round(m / (h**2)) # формула из вики и округление print('Индекс массы тела равен: ', index_mass) index(m,h) #запуск функции

DriveGlan

New member
#Банер bannr = """ ____ _ _ _ | __ ) ___ __| |_ _ _ __ ___ __ _ ___ ___ (_)_ __ __| | _____ __ | _ \ / _ \ / _` | | | | | '_ ` _ \ / _` / __/ __| | | '_ \ / _` |/ _ \ \/ / | |_) | (_) | (_| | |_| | | | | | | | (_| \__ \__ \ | | | | | (_| | __/> < |____/ \___/ \__,_|\__, | |_| |_| |_|\__,_|___/___/ |_|_| |_|\__,_|\___/_/\_\_ |___/ """ print(bannr) #Формула m = float (input("Введите ваш вес в кг: ")) h = float (input("Введите ваш рост в см: ")) h = h/100 #переводим в метры index_mass = float(m / (h*h)) # формула из википедиа #Условия, сокращение до 2х знаков после запятой: if float(index_mass) < 16: print ("Индекс тела равен:", "%.2f" % index_mass, "кг/м²", "и у Вас выраженный дефицит массы тела") elif float(index_mass) >= 16 and float(index_mass) = 18.5 and float(index_mass) = 18.5 and float(index_mass) = 25 and float(index_mass) = 30 and float(index_mass) = 35 and float(index_mass) = 40: print ("Индекс тела равен:", "%.2f" % index_mass, "кг/м²", "и у Вас очень резкое ожирение!") #Таблица Tab = """ ==================================================== |16 и менее Выраженный дефицит массы тела | |16—18,5 Недостаточная (дефицит) масса тела | |18,5—24,99 Норма | |25—30 Избыточная масса тела (предожирение) | |30—35 Ожирение | |35—40 Ожирение резкое | |40 и более Очень резкое ожирение | ==================================================== """ print (Tab)

Источник

BMI Calculator in Python – A Complete Step-By-Step Tutorial

Feautured Img BMI Cal

In this tutorial, we will understand what Body Mass Index or BMI is, how we can create a BMI calculator in the Python programming language.

What is Body Mass Index (BMI)?

BMI is dependent on a person’s height and weight. Also, people are classified as being underweight, overweight, or even obese based on their BMI value.

BMI Or Body Mass Index Infographic Chart

BMI can be used as a substitute for taking precise measurements of body fat percentages. Furthermore, BMI is a low-cost and simple way to check for those who may be at risk of health problems due to their weight.

BMI Calculator Implementation in Python

BMI is determined by dividing a person’s weight in kilograms twice by their height in meters, Here is the code for the BMI calculator written in Python:

h=float(input("Enter your height in meters: ")) w=float(input("Enter your Weight in Kg: ")) BMI=w/(h*h) print("BMI Calculated is: ",BMI) if(BMI>0): if(BMI<=16): print("You are very underweight") elif(BMI<=18.5): print("You are underweight") elif(BMI<=25): print("Congrats! You are Healthy") elif(BMI<=30): print("You are overweight") else: print("You are very overweight") else: print("enter valid details")

Let us understand the whole code line by line.

Line 1 and Line 2 – Taking input for height and weight of the person

Then we check if the BMI is greater than 0 or not as neither the weight nor the height can be negative hence BMI value can never be less than 0.

Now according to the BMI value, the person is categorized into underweight, healthy, and overweight using the if-else conditional statements.

Some Sample Outputs

Sample Output1 BMI

Sample Output2 BMI

Conclusion

I hope you understood BMI and how to implement and calculate the same in python. Try it yourself!

Want to learn more? Check out the tutorials mentioned below:

Источник

Оцените статью