Foreword#
Happy New Year! As the Spring Festival holiday comes to an end, everyone's life is gradually returning to normal. During this time, I have been quite idle, and since relatives rarely visit, I decided to write about the BMI calculation that I've always wanted to do.
What is BMI#
Body Mass Index, abbreviated as BMI, is an internationally used standard for measuring the degree of body fat and whether a person is healthy.
The calculation formula is: BMI = weight ÷ height². (Weight unit: kilograms; height unit: meters.)
BMI was first proposed by the Belgian polymath Quetelet in the mid-19th century.
Excerpt from Baidu Encyclopedia
In different countries, there are different standards for BMI, with the International Normal Standard being 20 – 25. This time, I used the PRC Standard (China Standard), where the PRC Normal Standard is 18.5 – 23.9.
Output Preview#
The parts with # are my explanations and are not present in the actual run.
Hello! Nice to meet you, what's your name?
Magneto # The value I entered
Ok! Magneto. Let's calculate your BMI and classification (adult)
Enter your weight (kg)
42 # The value I entered
Enter your height (m)
1.65 # The value I entered
Hi Magneto! Your BMI number is 15.426997245179065
Oh! Magneto! You're underweight and BMI is below standard.
The norm comes from PRC
Press Enter to exit
Full Code#
############################
### Date 2022 January 24 ###
### Author Magneto ###
### Name BMI Calculation <——>
### Facility iPad ###
### Language Python ###
############################
# Welcome screen
print("Hello! Nice to meet you, what's your name?") # String
the_name = input()
print(f"\nOk! {the_name}. Let's calculate your BMI and classification (adult)") # String
# Input values
print("\nEnter your weight (kg)")
weight = input()
print("\nEnter your height (m)")
height = input()
# Convert values
your_weight = float(weight)
your_height = float(height)
# Calculation
number = your_weight / (your_height * your_height)
the_number = float(number)
# Output value
print(f"\nHi {the_name}! Your BMI number is {the_number} \n") # String
# Analysis
if the_number < 18.5:
print(f"Oh! {the_name}! You're underweight and BMI is below standard.")
elif 18.5 <= the_number <= 23.9:
print(f"{the_name}, your BMI is normal.")
elif 23.9 < the_number <= 27.9:
print(f"{the_name}, you're overweight and BMI is higher than the standard.")
elif 27.9 < the_number <= 32:
print(f"{the_name}, you're too fat and BMI is well above the mark")
else:
print(f"{the_name}, you're severely exceeding the limit, please lose weight")
print("\nThe norm comes from PRC")
x = input('Press Enter to exit')
Code Analysis#
Analysis Description#
The code analysis will specifically describe the type of code used in each line, its purpose, and how to use it, including the lines occupied by comments.
Comments#
In Python, comments are marked with a hash symbol #. The content after the hash will be ignored by the Python interpreter. In this program, lines 1-8, line 12, line 17, line 23, and line 25 are all comments.
Example #1
# Welcome screen
print("Hello! Nice to meet you, what's your name?")
The Python interpreter will ignore the first line and only execute the second line.
Hello! Nice to meet you, what's your name?
What is the purpose of comments?
The main purpose of writing comments is to explain what the code is doing and how it works. During development, you may be very familiar with how different parts work together, but after some time, you might forget some details. Of course, you can determine how each part works by studying the code, but writing comments allows you to summarize that section of code in clear natural language, saving a lot of time when you revisit that code later.
Currently, most software is collaboratively written, and the authors may be multiple employees from the same company or developers from the same open-source project. To facilitate collaboration, comments are essential, so it's best to write comments from the beginning.
User Input#
Most programs are designed to solve problems for end users, which requires obtaining some information from them. Therefore, user input is very necessary, and in Python, the function input()
can effectively solve this problem. In this program, this function is used in lines 10, 14, 16, and 37.
Example #1
# Basic input() usage
Message = input("Hello World")
print(Message)
After executing this code, the following will be displayed:
Hello World
After execution, the program will wait for user input, and after the user presses Enter, it will continue running. The input value is assigned to the variable Message
, and the subsequent print(Message)
will present the input content to the user:
Hello WorldImMagneto
ImMagneto
In formal programs, we rarely use the above method; instead, we use clearer methods that accurately indicate what kind of information we want the user to provide — specifying what the user should input.
Example #2
name = input("Please enter your name:")
print(f"\nHello {name}!")
After running and interacting, it will look like this:
Please enter your name: Magneto
Hello Magneto!
In this program, I used a separated writing style to make the statements clearer.
Example #3
print("Hello! Nice to meet you, what's your name?")
the_name = input()
print(f"\nOk! {the_name}. Let's calculate your BMI and classification (adult)")
By combining print()
and input()
, the code becomes clearer and more readable.
Hello! Nice to meet you, what's your name?
Magneto
Ok! Magneto. Let's calculate your BMI and classification (adult)
However, there is no change in the user-facing content, but this is a good writing style in large project development, as it effectively reduces the occurrence of bugs and only calls the user-written content at specified locations.
Converting Integers and Strings to Floating Point Numbers#
To perform necessary calculations and displays, we must convert integers and strings to floating point numbers, so we need to introduce a function – float()
float() Method Syntax
class float([x])
Where x represents an integer or string, and after running, it will return a floating point number.
Example #1
>>> float(1)
1.0
>>> float(112)
112.0
>>> float(-123.6)
-123.6
>>> float('123') # String
123.0
In this program, floating point numbers are needed for calculations, and to follow a clear writing method, I used a separated writing style.
Example #2
# Calculation
number = 51.2 / (1.6 * 1.6)
the_number = float(number)
# Output value
print(f"Your BMI number is {the_number}")
The final output will be:
Your BMI number is 20.351562499999996
Floating point numbers will round off when encountering infinite decimals.
User input values cannot be calculated directly; they need to be converted to floating point numbers for calculations. Interestingly, user input values are also integers and strings, so the float()
function can also be used for conversion.
Example #3
# Input values
print("\nEnter your weight (kg)")
weight = input()
print("\nEnter your height (m)")
height = input()
# Convert values
your_weight = float(weight)
your_height = float(height)
# Calculation
number = your_weight / (your_height * your_height)
the_number = float(number)
# Output value
print(f"\nYour BMI number is {the_number}")
After running, it looks like this:
Enter your weight (kg)
51.2
Enter your height (m)
1.6
Your BMI number is 20.351562499999996
if-elif-else Statement#
We need to check two or more different situations, for which we can use the if-elif-else
structure. It checks each condition in order until it encounters a condition that passes. Once a condition passes, it will execute the subsequent code and skip the remaining code under the if-elif-else
statements. To explain more conveniently, it is better to provide examples than to write usage.
Example #1
The requirements we need:
If the BMI value is less than 18.5, tell them they are below the standard value.
If the BMI value is greater than or equal to 18.5 and less than or equal to 23.9, tell them they meet the standard value.
If the BMI value is greater than 23.9 but less than or equal to 27.9, tell them they exceed the standard value.
Through mathematical intervals, we know that these values fall within the range of (-∞,27.9]
, and all values outside this range are severely exceeding the standard, so we need to inform them that they are severely exceeding the standard value.
Based on these requirements, the if-elif-else
statement we need looks like this:
# Analysis
if the_number < 18.5:
print(f"You're underweight and BMI is below standard.")
elif 18.5 <= the_number <= 23.9:
print(f"Your BMI is normal.")
elif 23.9 < the_number <= 27.9:
print(f"You're overweight and BMI is higher than the standard.")
elif 27.9 < the_number <= 32:
print(f"You're too fat and BMI is well above the mark")
else:
print(f"You're severely exceeding the limit, please lose weight")
The previous if-elif
includes all numbers within the interval (-∞,27.9]
, so else
only includes the part that is (27.9,+∞)
, which is severely exceeding the standard value.
Next, let's assume the value is 20.
the_number = 20
if the_number < 18.5:
print(f"You're underweight and BMI is below standard.")
elif 18.5 <= the_number <= 23.9:
print(f"Your BMI is normal.")
elif 23.9 < the_number <= 27.9:
print(f"You're overweight and BMI is higher than the standard.")
elif 27.9 < the_number <= 32:
print(f"You're too fat and BMI is well above the mark")
else:
print(f"You're severely exceeding the limit, please lose weight")
Then we will get the following content:
Your BMI is normal.
Due to the if-elif-else
statement and Python's characteristics, this part of the content is very close to natural language, so the method of translation will be very applicable, and the specific translation will not be displayed.
Conclusion#
A year ago, I discussed with many friends about those great programmers who can accomplish tasks that take others hundreds of lines of code with just a few lines. They are very powerful, and everyone needs sufficient accumulation to become that kind of great programmer. I do not deny the existence of such people, nor do I deny their strength, but in my understanding, true programming ability is the ability to clearly present what you have written, to clearly and concisely tell everyone what this part does and what that part does, rather than completing it in one go. This is the meaning of programming. Of course, appropriate shortening can also better express one's meaning, just like idioms in natural language. The reason this issue is called "BMI Calculation for the Future" is precisely because of this. In future programming, it will only be clear code, which is why I wrote the analysis of the code in a standardized and clear manner throughout, aiming for the future!
This article is synchronized and updated to xLog by Mix Space. The original link is https://fmcf.cc/posts/technology/Python_Notes_3