Or the newer technique: print('Your BMI =. You could write: print('Your BMI = %f You are %s.' % (body_mass_index, category)) You can refer to for documentations and examples. Python offers many tools to format strings so that you do not need to use string concatenations. Going further, a few more details could be improved. Height_in_meter = convert_feet_to_meter(height_in_feet)īody_mass_index = get_body_mass_index(height_in_meter, weight_in_kilo) Height_in_feet = float(input('Enter your height in feet:')) Weight_in_kilo = float(input('Enter your weight in kilo:')) Return weight_in_kilo / (height_in_meter ** 2) Return height_in_feet * INCHES_PER_FOOT * METERS_PER_INCHĭef get_body_mass_index(height_in_meter, weight_in_kilo): This allows the interactivity to be triggered as needed.Īt this stage, we have: INCHES_PER_FOOT = 12ĭef convert_feet_to_meter(height_in_feet): As pointed out by Solomon Ucko, it's generally a good idea to have this performed via a main() function and have the last two (non-blank) lines be if _name_ = '_main_': main(). Thus, the usual strategy is the following: split your code into 2 parts:Ĭode defining functions/constants/classes/etc but without any side-effect or user interactionsĬode actually doing things (input/output, etc) behind an if _name_ = "_main_": guard. Currently, if we do so, we get stuck into the parts asking for user inputs. It highlights how to solve problems you may not be interested in yet but it is a good chance to do things properly.Īlso, if we want to be able to actually reuse your functions, we want to be able to import the file. In our case, defining functions could be a nice touch.ĭisclaimer: Next paragraph can be a bit overwhelming for a beginner, do not worry if you do not fully get it. To make the code easier to understand (and easier to reuse, to test, etc), it is a good habit to split in into smaller reusable chunks. Similarly, half the checks have no effect. Print('Your BMI = ' + str(body_mass_index) + ' You are ' + category + '.')īecause of the way we check body_mass_index, if it is under 15, we get into the first case so there is no need to check elif 15 <= body_mass_index in the else part. This is very specific to Python but instead of body_mass_index > 30 and body_mass_index 40: In your case, we could store the body category in a variable and only print the ouput from a single place: One of the principles of software programming is Don't Repeat Yourself (also written DRY). Having duplicated code makes the code more tedious to read and harder to maintain (if you need to change something, you'll need to change it in many places). This could be used at the beginning of the function as well.Ī lot of code looks like the same line with minimal variations.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |