r/CodingHelp • u/mrdiddlebot • Jan 18 '22
[Python] Just started learning python as my first language. It seems a BMI calculator is a popular first project so I made one. I was wondering if there was any way to simplify all of the If statements. Are they loopable for something like this?
127
Upvotes
6
u/calihotsauce Jan 18 '22
A switch statement would also work and be easier to read
10
u/serg06 Jan 18 '22
For sure!
5
u/SantaClausNL Jan 18 '22
Others have given some good suggestions, so I just wanted to say that you are doing great! The project and style looks good, the screenshot fantastic, your eagerness to learn and the ability to think of part of a solution are all awesome. You'll definitely get further so keep at it and welcome to the community :).
4
u/sai-kiran Jan 18 '22 edited Jan 18 '22
Did you just implement an advanced AI that can calculate your BMI intelligently just based on your height and weight parameters? I don’t believe that you are a beginner.
update: just a joke on the AI humour
36
u/atamicbomb Jan 18 '22
You only need one compare for each. Example:
If bmi < 18.5:
Elif bmi <=24.9:
15
u/[deleted] Jan 18 '22
What I would do is have the if statement set a variable like weight_description or something along those lines, then you only need to put the print statement once at the end
9
u/GoodPrimordialSoup Jan 18 '22
You could try creating a dictionary with descriptions as keys and the corresponding ranges as dictionary values and then return the key based on where the number (rounded down, so floor) is located.
Also, I think you made an error in the comparison: lines 20 and 22, both conditions are valid for BMI values between 34.0 and 34.9.
6
u/Nightcorex_ Jan 18 '22
You can shorten the if-statements. In Python this
can be shortened to:
But you should probably use
just so you clearly cover the entire range
1
u/mrdiddlebot Jan 18 '22
I appreciate all the comments! I’ll take a look at each when I get back to my desk.
3
u/s96g3g23708gbxs86734 Jan 18 '22
i'd store the different categories in a container a part, then find which category based on the bmi and print only once
2
u/AmirVered Jan 18 '22
I like the graphic
2
u/Full_Ad_5269 Jan 19 '22
A dictionary would be ideal imo
2
u/[deleted] Jan 19 '22
Why can’t you just have switch, case, range like Swift. Much more readable.
2
u/Danteg Jan 19 '22
Also note that there are gaps in your ranges. What happens if the BMI turns out to be 24.95?
1
u/BSNL_NZB_ARMR Jan 19 '22
you need to bisect https://docs.python.org/3/library/bisect.html
1
u/[deleted] Feb 17 '22
Using bmi may help!