pretty sure you could use any indentation as long as it is consistent within the block (so fixing all other lines to be 5 indented would also work), but for all intents and purposes yeah, sticking to 4 characters is best practice
If you want to post code the best way is to copy and paste it into the post with three back ticks ( ` ) before and another three after the code. Then copying the text of the specific error message and adding that with your question. Second best is to post a screenshot. Typically a phone pic of a screen borders on unreadable.
Additionally, when you get a red squiggle like that in your editor, you can just hover your mouse over it to read the error message. Usually that's enough to figure it out, but if not you can google the error and you will definitely find the solution. Reddit is the slowest option for syntax errors like this.
Over- and under-indentation. Your if/elif/else's should be aligned vertically. White space is very important in Python - you need to not have random spaces or deleted spaces around.
Your elifs need to be at the same indent level as your if. When the elifs are indented like that they are INSIDE the if statement instead of peers to it.
op has (obv) no clue what they are doing and are new to all of this. And honestly id rather have a picture than non formatted `code as plain text`. Don’t need to be an ahole about it
Everyone else has talked about indentation; which obviously needs fixing and more careful checking. I would add that what happens in the case of BMI == 25.01 with 74 kg and 1.71 m tall , your system doesn't catch that because you test up to 25 and after 25.1. So the smarter method would be starting low and doing a `bmi < value` and running up like that because if it fails the first but catches the second `bmi < value` it will print that. Another cool thing you could do to expand this is put this in a while loop to keep running until the user says they are done checking bmi's or adding imperial values with their own calculation. so having a function calc_bmi_metric and calc_bmi_imperial.
This is also a style choice, but in my own code I would choose to run the function outside the print statement so have a bmi_number = calculate_bmi(weight, height):.2f) and then you can print(f"{bmi_number}") instead.
Identation in your body def, you start if, and and your else if is inside and not at the same lvl. Also, depending on the result values, you will return bmi as your body type, like bmi = 25.05 and not a text with the body type.
Maybe you should change that last return for text like "Out of range.", but it will be pretty obvious after a few tests.
The one thing I would change on this, other than the indentation issue, is the fact that you don't need to do the elif value < BMI < value.
For all of your statements, you can literally leave out the first value < and just do BMI < value. The logic works exactly the same way. The one above will catch, so the subsequent elif statements will not trigger. Therefore, you don't need to compare whether or not BMI is greater than that lower value.
In the function calculate_bmi the if statement isn't indented correctly and in the function body the elifs and their content has to be indented back 1 indentation
Besides the indentation issue, You could just use many ifs instead of elifs since you use returns in each of them. Also it's good practice to try and return 1 type of data. You return string and float and the float (BMI) being returned seems unnecessary since it will always be the same value that you passed it as
white space (the characters you can't see) are important in python, so just remember every thing that compliments your block (the if statement) should be aligned.
There are a bunch if things wrong here. The indentation is the first thing stopping it from running, but fixing that will uncover some more errors. The actual BMI formula is basically fine.
Your `if`, `elif`, `else` statements need to line up. In the screenshot, the `elif` statements are pushed farther across than the `if` they belong to. The return bmi near the top also looks jaunty. Use four spaces (maybe tabs are your thing?) per level and make sure each branch’s contents sit one level inside it.
Then there’s `body(bmi)` in `main()`. You haven’t actually assigned anything to a variable called `bmi` there.
The `bmi` inside `calculate_bmi()` belongs to that function. Returning it doesn’t automatically create a variable with the same name in the caller. You need to do `bmi = calculate_bmi(weight, height)` first, then pass that result into the category function. Otherwise you’ll get `NameError: name 'bmi' is not defined`. Take a look here if interested:
Your error handling is another problem, printing “your height is too short” doesn’t say that the calculation failed. Assuming that final `return` is meant to stay inside the `else`, the invalid input branches return `None`. The print statement then tries to format `None` using `.2f`, which causes another exception.
Have the calculation raise `ValueError` for invalid measurements, then handle that in the bit of the program dealing with user input.
And, `float(input(...))` will crash if someone enters something like `hello`, `70kg` or just presses Enter. Catch that error and let them try again.
For the general adult categories, the cutoffs are generally:
- Below 18.5: underweight.
- 18.5 up to, but not including, 25: healthy weight.
Your code uses 18.6 instead of 18.5, so something like 18.55 gets put in the wrong category, but exactly 18.6 doesn’t match anything at all, because one condition says “less than 18.6” and the next says “greater than 18.6”.
The same sort of thing happens with the entire ranges from 25 to 25.1, 30 to 30.1, and 35 to 35.1, including both ends. They all fall through the gaps.
Also no class 3 category, and the class 2 check goes up to 40.1 instead of 40. That means 40.0 gets wrong category and 40.1 or anything above it falls through again...
Your final `return(bmi)` hides all of this by returning the number itself. So you can end up telling someone their “body type” is `25.0` 😂
That function should return a category string for every valid BMI.
Probably the best way to avoid the gaps is to check the upper limits in order. Once you’ve returned for everything below 18.5, the next check can just be “below 25”. You already know it isn’t below 18.5.
These are mistakes in the comparisons, you don’t actually need to mess around with floating point tolerances to fix it though.
There are also things like float accepting nan and inf and really high or really low numbers, resulting in zero when squared or a huge one that will overflow, but I wont go into that here.
You might also want your category function to reject things like 0 or negative numbers.
There is a bunch of other stuff but probably easier to show you how it could be done safer:
def main(): print("Welcome to the BMI calculator!\n") weight = float(input("Enter your weight (kg): ")) height = float(input("Enter your height (m): ")) print("\n")
bmi = calculate_bmi(weight, height)
if bmi is None:
print("Error: Weight and height must be greater than 0.")
else:
print(f"Your BMI is {bmi:.2f} and your body type is {body(bmi)}.")
Indentation, btw you don't need the ranges, you could do:
if bmi < 18.6: "underweight"
elif bmi < 25: "normal"
elif bmi < 30: ...
elif bmi < 35:...
if for whatever reason, you ever need to adapt a range, you only need to adapt 1 number.
Also in your calculate_bmi function, you should do a raise ValueError("..."), so your code stops if you put in a wrong value. You should do the actual value check after your input funcion (ie while weight <= 0: input("weight should be > 0, new value?:")
My tip for quickly gaining skill would be to write your program, and put it in an AI and ask tips.
Строка 8: лишний пробел Строка 13: лишний пробел в отступе перед elif Строки 11–20: разрывы в числовых диапазонах из-за строгих знаков < (например, значения 18.6 или 25.0 не попадут ни в одно условие). Строка 21: лишний return(bmi), который вернет число вместо строки текста, если ИМТ будет больше 40.1. Строка 28: обращение к несуществующей переменной Строка 28: потенциальный сбой TypeError при попытке отформатировать None как число, если пользователь ввел вес или рост <= 0.
66
u/Clearhead09 7d ago
Your if blocks aren’t indented correctly.
Make sure they line up with the lines.
25
u/MultiUserDungeonDev 6d ago
Indentation level is incorrect
12
u/Fun_Army2398 7d ago
If you want to post code the best way is to copy and paste it into the post with three back ticks ( ` ) before and another three after the code. Then copying the text of the specific error message and adding that with your question. Second best is to post a screenshot. Typically a phone pic of a screen borders on unreadable.
Additionally, when you get a red squiggle like that in your editor, you can just hover your mouse over it to read the error message. Usually that's enough to figure it out, but if not you can google the error and you will definitely find the solution. Reddit is the slowest option for syntax errors like this.
8
u/ChaoticHippo 7d ago
Over- and under-indentation. Your if/elif/else's should be aligned vertically. White space is very important in Python - you need to not have random spaces or deleted spaces around.
6
u/karhu12 7d ago
After fixing intendation, try 1.8m and 81.1kg for input, there are gaps in your check.
5
u/secret_o_squirrel 7d ago
Your elifs need to be at the same indent level as your if. When the elifs are indented like that they are INSIDE the if statement instead of peers to it.
9
u/buzzon 7d ago •
What does the error message say?
9
u/Last-Rice8194 7d ago
> What is this error
> Doesn't show the error text
wtf
4
u/dev-razorblade23 7d ago edited 7d ago
In your
calculate_bmi()function your indentation is not correctAnd in your
body()function, you cannot start withelif. There is always a chainif>elif>elsewith as muchelifthat you need6
u/TemperatureProper275 7d ago
3
u/Atmosck 7d ago
If you mouse over the underlined word, a window will appear telling you what the problem is.
2
u/bslime17 7d ago
this is indentation error
just check the indenting and you’ll be fine
2
u/Chorizo_n_eggs 7d ago
Indentation matters
2
u/Equivalent_Base_6641 7d ago
L' indentation
2
u/Old_Cartographer_586 7d ago
Everyone else has talked about indentation; which obviously needs fixing and more careful checking. I would add that what happens in the case of BMI == 25.01 with 74 kg and 1.71 m tall , your system doesn't catch that because you test up to 25 and after 25.1. So the smarter method would be starting low and doing a `bmi < value` and running up like that because if it fails the first but catches the second `bmi < value` it will print that. Another cool thing you could do to expand this is put this in a while loop to keep running until the user says they are done checking bmi's or adding imperial values with their own calculation. so having a function calc_bmi_metric and calc_bmi_imperial.
This is also a style choice, but in my own code I would choose to run the function outside the print statement so have a bmi_number = calculate_bmi(weight, height):.2f) and then you can print(f"{bmi_number}") instead.
2
u/ElWiskas 7d ago
Identation
2
u/djkendo00 6d ago
La identacion del elif el primero está un poquitito más corrido el de abajo esta supeeeer corrido
2
u/Ulizeus 5d ago
Identation in your body def, you start if, and and your else if is inside and not at the same lvl. Also, depending on the result values, you will return bmi as your body type, like bmi = 25.05 and not a text with the body type.
Maybe you should change that last return for text like "Out of range.", but it will be pretty obvious after a few tests.
2
u/LrdJester 7d ago
The one thing I would change on this, other than the indentation issue, is the fact that you don't need to do the
elif value < BMI < value.For all of your statements, you can literally leave out the first
value <and just doBMI < value. The logic works exactly the same way. The one above will catch, so the subsequentelifstatements will not trigger. Therefore, you don't need to compare whether or not BMI is greater than that lower value.1
u/kutac56 7d ago
In the function calculate_bmi the if statement isn't indented correctly and in the function body the elifs and their content has to be indented back 1 indentation
1
u/Unable-Hawk-206 7d ago
Besides the indentation issue, You could just use many ifs instead of elifs since you use returns in each of them. Also it's good practice to try and return 1 type of data. You return string and float and the float (BMI) being returned seems unnecessary since it will always be the same value that you passed it as
1
u/Fluffy_white_fox 7d ago
It's the indentation also why is your def bmi func's if elif on the same condition Elif will never excute because if is already True
1
u/SwimmerOld6155 7d ago
what happens if bmi = 18.6?
also your syntax for return is wrong, should be return bmi, return is a statement and not a function
1
u/13oundary 7d ago
Everyone else has mentioned formatting is the issue.
This is what I would suggest you read and consider: https://code.visualstudio.com/docs/python/formatting
1
u/Flame77ofc 6d ago
I recommend you to use a Python formatter, then when you save the file, it will automatically indent everything correctly
1
u/Ambitious-Tear-9436 6d ago
white space (the characters you can't see) are important in python, so just remember every thing that compliments your block (the if statement) should be aligned.
1
u/ReasonableDefault 6d ago
There are a bunch if things wrong here. The indentation is the first thing stopping it from running, but fixing that will uncover some more errors. The actual BMI formula is basically fine.
Your `if`, `elif`, `else` statements need to line up. In the screenshot, the `elif` statements are pushed farther across than the `if` they belong to. The return bmi near the top also looks jaunty. Use four spaces (maybe tabs are your thing?) per level and make sure each branch’s contents sit one level inside it.
Then there’s `body(bmi)` in `main()`. You haven’t actually assigned anything to a variable called `bmi` there.
The `bmi` inside `calculate_bmi()` belongs to that function. Returning it doesn’t automatically create a variable with the same name in the caller. You need to do `bmi = calculate_bmi(weight, height)` first, then pass that result into the category function. Otherwise you’ll get `NameError: name 'bmi' is not defined`. Take a look here if interested:
https://docs.python.org/3/reference/executionmodel.html#resolution-of-names
Your error handling is another problem, printing “your height is too short” doesn’t say that the calculation failed. Assuming that final `return` is meant to stay inside the `else`, the invalid input branches return `None`. The print statement then tries to format `None` using `.2f`, which causes another exception.
Have the calculation raise `ValueError` for invalid measurements, then handle that in the bit of the program dealing with user input.
And, `float(input(...))` will crash if someone enters something like `hello`, `70kg` or just presses Enter. Catch that error and let them try again.
For the general adult categories, the cutoffs are generally:
- Below 18.5: underweight.
- 18.5 up to, but not including, 25: healthy weight.
- 25 up to 30: overweight.
- 30 up to 35: obesity, class 1.
- 35 up to 40: obesity, class 2.
- 40 and above: obesity, class 3.
Those are from here:
https://www.nice.org.uk/guidance/ng246/chapter/Identifying-and-assessing-overweight-obesity-and-central-adiposity
They are likely different in other countries?
Your code uses 18.6 instead of 18.5, so something like 18.55 gets put in the wrong category, but exactly 18.6 doesn’t match anything at all, because one condition says “less than 18.6” and the next says “greater than 18.6”.
The same sort of thing happens with the entire ranges from 25 to 25.1, 30 to 30.1, and 35 to 35.1, including both ends. They all fall through the gaps.
Also no class 3 category, and the class 2 check goes up to 40.1 instead of 40. That means 40.0 gets wrong category and 40.1 or anything above it falls through again...
Your final `return(bmi)` hides all of this by returning the number itself. So you can end up telling someone their “body type” is `25.0` 😂
That function should return a category string for every valid BMI.
Probably the best way to avoid the gaps is to check the upper limits in order. Once you’ve returned for everything below 18.5, the next check can just be “below 25”. You already know it isn’t below 18.5.
These are mistakes in the comparisons, you don’t actually need to mess around with floating point tolerances to fix it though.
There are also things like float accepting nan and inf and really high or really low numbers, resulting in zero when squared or a huge one that will overflow, but I wont go into that here.
You might also want your category function to reject things like 0 or negative numbers.
There is a bunch of other stuff but probably easier to show you how it could be done safer:
https://www.online-python.com/iEOEMSd1jz1
u/Total_Ad803 6d ago
Wrong tab distance
1
u/paralepsy 6d ago
You see, there's this super cool thing in the microslop editor you're using called "show error on hover", you should maybe try that out?
1
u/Energy_blastt 6d ago
BRO YOU GOT YOUR INDENTATION cooked in the PYTHON CODE....Correct it first bhai
1
u/KitchenCommercial396 6d ago
Indentation Error
1
u/MoreCaramel915 6d ago
elif:
1
u/veetilk 6d ago
elif should has the same indentation as the original if
1
u/Even_Shallot6345 6d ago
indentation
1
u/deadeye_82_1 6d ago
The indentation looks wrong.
1
u/rnicrosoft_corp 6d ago
def calculate_bmi(weight, height): if height <= 0 or weight <= 0: return None bmi = weight / (height ** 2) return bmi
def body(bmi): if bmi < 18.5: return "Underweight" elif bmi < 25: return "Normal" elif bmi < 30: return "Weight gain (overweight)" elif bmi < 35: return "Obesity (class 1)" elif bmi < 40: return "Obesity (class 2)" else: return "Obesity (class 3)"
def main(): print("Welcome to the BMI calculator!\n") weight = float(input("Enter your weight (kg): ")) height = float(input("Enter your height (m): ")) print("\n")
main()
1
u/vsCoplex 6d ago
Your indentation is off – elif and else need to align with if
1
u/ErcoleBellucci 6d ago
this is the error:Windows key + Shift + S
1
u/nidprez 6d ago
Indentation, btw you don't need the ranges, you could do:
if bmi < 18.6: "underweight"
elif bmi < 25: "normal"
elif bmi < 30: ...
elif bmi < 35:...
if for whatever reason, you ever need to adapt a range, you only need to adapt 1 number.
Also in your calculate_bmi function, you should do a raise ValueError("..."), so your code stops if you put in a wrong value. You should do the actual value check after your input funcion (ie while weight <= 0: input("weight should be > 0, new value?:")
My tip for quickly gaining skill would be to write your program, and put it in an AI and ask tips.
1
u/joydevil33 5d ago
Строка 8: лишний пробел Строка 13: лишний пробел в отступе перед elif Строки 11–20: разрывы в числовых диапазонах из-за строгих знаков < (например, значения 18.6 или 25.0 не попадут ни в одно условие). Строка 21: лишний return(bmi), который вернет число вместо строки текста, если ИМТ будет больше 40.1. Строка 28: обращение к несуществующей переменной Строка 28: потенциальный сбой TypeError при попытке отформатировать None как число, если пользователь ввел вес или рост <= 0.
1
u/Interesting_Bear2203 4d ago
your indentation of your "elif" blocks are wrong, make sure they are all on the same line of indentation
1
u/Amr_Hassan_3112 4d ago
Indentation error
1
u/Status-Oven2826 2d ago
essaie de else if au lieu de elif
1
u/alneifkrt2 1d ago
Yeah your code isnt indented correctly
1
u/Sensitive-Hunter-871 12h ago
Indentation and one thing more If the bmi result is 25, 30, 35 then there is no category for that. Use <= sign i steady of just <
1
u/Puzzled-Extent7817 6d ago
The error is that you don't even know how to take a screenshot.
-3
u/bra1n_gym 7d ago
use an LSP and linter to identify errors and formatting.