+ 2

How can I make my code DRYer?

This is my code: https://code.sololearn.com/cVGOZtrwGBm0/?ref=app any suggestions?

20th Jun 2017, 6:49 AM
Massimiliano Orsini
8 Answers
+ 3
just a tip, u can put a String as variable and just print once at the end like: String s if (x < 16): s = "overweigth" print(s)
20th Jun 2017, 7:04 AM
Juliano Ventola
Juliano Ventola - avatar
+ 2
Now that you've done that, since your conditions are all regular, you can turn this into a loop (I didn't test this): weight_msgs = [ (15.0, "Very severely underweight"), (16.0, "Severely underweight"), (18.5, "Underweight"), (25.0, "Healthy weight"), (30.0, "Overweight"), (35.0, "Moderately obese"), (40.0, "Severely obese"), ] for weight, msg in weight_msgs: if weight < ris: s = msg break else: s = "Very severely obese" Here's what I did: - changed all weights to use the same type (float) - used a for-else construct described here: https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops - changed "Healthyeight" to "Healthy weight" - changed "Moderatley" to "Moderately" [edited] added a missing break
20th Jun 2017, 9:54 AM
Igor B
Igor B - avatar
+ 2
And you can even avoid the for-else clause, if you use a sentinel value for the last case: a very large weight which makes the final "if" always true: weight_msgs = [ (15.0, "Very severely underweight"), (16.0, "Severely underweight"), (18.5, "Underweight"), (25.0, "Healthy weight"), (30.0, "Overweight"), (35.0, "Moderately obese"), (40.0, "Severely obese"), (1000000.0, "Very severely obese"), ] for weight, msg in weight_msgs: if weight < ris: s = msg break
20th Jun 2017, 10:00 AM
Igor B
Igor B - avatar
+ 1
Honestly, nothing really comes to mind outside of maybe abstracting that logic with your conditionals​ and placing that in it's own function.
20th Jun 2017, 7:17 AM
Don
Don - avatar
+ 1
You don't need the first part of every "and" expression since that possibility has already been eliminated by the previous condition failing. E.g., this code: if ris < 15: s = "Very severely underweight" elif ris >= 15 and ris < 16: s = "Severely underweight" is equivalent to: if ris < 15: s = "Very severely underweight" elif ris < 16: s = "Severely underweight" since in order to even get to the "elif" part, the "if" must have failed.
20th Jun 2017, 9:27 AM
Igor B
Igor B - avatar
+ 1
Since I m new to coding and I'm not good in english It will take time to me to understand that loop. Anyway thank you for your help.
20th Jun 2017, 10:16 AM
Massimiliano Orsini
0
@Don How can I do that?
20th Jun 2017, 7:56 AM
Massimiliano Orsini
0
Right, thank you!
20th Jun 2017, 9:32 AM
Massimiliano Orsini