Python Learning Diary – BMI Calculator
Preface
Happy New Year! As the Spring Festival holiday comes to an end, everyone's life is gradually returning to normal. During this period, I've been idle, rarely visiting relatives, so I wrote the BMI calculator I've always wanted to write.
What is BMI
Body Mass Index, abbreviated as BMI, is a standard commonly used internationally to measure how thin or fat a person is and whether they are healthy.
The 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.
Excerpted from Baidu Baike
BMI standards vary from country to country. The International Normal Standard is 20–25, while this time I used the PRC Standard (Chinese standard), where the PRC Normal Standard is 18.5–23.9.
Output Preview
The parts with # are my explanations; they are not present in the actual run.
Hello!Nice to meet you what's your name?
Magneto # my input
Ok!Magneto. Let's calculate your BMI and classification(adult)
Enter your weight(kg)
42 # my input
Enter your height(m)
1.65 # my input
Hi Magneto!Your BMI number is 15.426997245179065
Oh!Magneto!You're underweight and BMI is below standerd.
The norm come from PRC
Press Enter to exit
Full Code
############################
### Date 2022 January 24 ###
### Author Magneto ###
### Name BMI计算 <——>
### 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)
#Calculate
number = your_weight/(your_height*your_height)
the_number = float(number)
#Output result
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 standerd.")
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 well above the mark")
else:
print(f"{the_name},you're severely exeed the limit please lose weight")
print("\nThe norm come from PRC")
x = input('Press Enter to exit')
Code Analysis
Analysis Notes
The code analysis will explain in detail what type of code is used on each line, what it does, and how to use it. The line numbers include comment lines.
Comments
In Python, comments are marked with the hash symbol #. Everything after the hash is ignored by the Python interpreter. In this program, lines 1–8, 12, 17, 23, and 25 are 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 does and how it does it. During development, you know exactly how each part works together, but after a while, you may forget some details. Of course, you can study the code to figure out how each part works, but by writing comments, you can summarize the code in clear natural language, which will save a lot of time when you revisit the code later.
Currently, most software is written collaboratively, either by multiple employees of the same company or by developers of the same open-source project. To facilitate collaboration, comments are essential, so it's best to write comments for your programs from the start.
User Input
Most programs are designed to solve problems for end users, and to do that, they need to obtain information from the user. Therefore, user input is essential. In Python, the input() function can effectively solve this problem. In this program, lines 10, 14, 16, and 37 use this function.
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 waits for user input and continues running after the user presses Enter. The input value is assigned to the variable Message, and the subsequent print(Message) will display the input content to the user:
Hello WorldImMagneto
ImMagneto
In real programs, we rarely use the above method. Instead, we use a clearer approach that precisely indicates what information we want the user to provide—pointing out 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 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 separating 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)
There is no change in user-facing content, but this is a good writing style in large projects because it effectively reduces the occurrence of bugs and only calls user-written content at specified locations.
Converting Integers and Strings to Floats
To perform necessary calculations and display, we must convert integers and strings to floating-point numbers. Therefore, we need to introduce a function – float().
float() method syntax
class float([x])
Here, x represents an integer or string, and after execution, it returns 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, we need to perform calculations with floating-point numbers, and to follow a clear writing style, we use a separated approach.
Example #2
#Calculate
number = 51.2/(1.6*1.6)
the_number = float(number)
#Output result
print(f"Your BMI number is {the_number}")
The final output is like this:
Your BMI number is 20.351562499999996
Floating-point numbers are rounded when they encounter infinite decimals.
The values entered by the user cannot be directly used in calculations; they need to be converted to floating-point numbers. Fortunately, the user's input is exactly integers or strings, so we can also use the float() function 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)
#Calculate
number = your_weight/(your_height*your_height)
the_number = float(number)
#Output result
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 Statements
We need to check two or even more different conditions, so we can use the if-elif-else structure. It checks each condition test in order until it finds one that passes. Once a test passes, the code after it is executed, and the rest of the if-elif-else block is skipped. To make it easier to explain, giving an example is better than describing the usage.
Example #1 Our requirements:
- If the BMI value is less than 18.5, tell the user they are below the standard.
- If the BMI value is greater than or equal to 18.5 and less than or equal to 23.9, tell the user they are within the standard.
- If the BMI value is greater than 23.9 but less than or equal to 27.9, tell the user they exceed the standard.
Using mathematical intervals, we know that these values cover the interval (-∞,27.9]. All values outside this range are severely above the standard, so we should tell the user they are severely exceeding the standard.
Based on these requirements, our if-elif-else statement looks like this:
#Analysis
if the_number < 18.5:
print(f"You're underweight and BMI is below standerd.")
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 well above the mark")
else:
print(f"You're severely exeed the limit please lose weight")
The preceding if-elif covers all numbers in the interval (-∞,27.9], so else only covers (27.9,+∞), which is the part that severely exceeds the standard.
Now let's assume the value is 20:
the_number = 20
if the_number < 18.5:
print(f"You're underweight and BMI is below standerd.")
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 well above the mark")
else:
print(f"You're severely exeed the limit please lose weight")
Then we will get the following:
Your BMI is normal.
Because of the if-elif-else statement and Python's characteristics, this part is very close to natural language, so a translation approach is very suitable, and the specific translation will not be shown.
Conclusion
A year ago, I discussed with many friends about those experts who can accomplish in a few lines of code what others need hundreds of lines to do. They are truly powerful, and everyone needs sufficient accumulation to become such an expert. I won't deny the existence of such people, nor their power, but in my understanding, truly good programming ability is the ability to clearly present what you write, to clearly and concisely tell everyone what this part does and what that part does, rather than doing it all in one go. That is the meaning of programming. Of course, appropriate shortening can also better express your meaning, just like idioms in natural language - Chinese. This is also why this issue is called "Future-Oriented BMI Calculator". In future programming, only clear code will exist. For this reason, I wrote the code analysis in a standardized and clear manner throughout. This is to face the future!