+ 2
How can I make my code DRYer?
This is my code: https://code.sololearn.com/cVGOZtrwGBm0/?ref=app any suggestions?
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)
+ 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
+ 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
+ 1
Honestly, nothing really comes to mind outside of maybe abstracting that logic with your conditionalsâ and placing that in it's own function.
+ 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.
+ 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.
0
@Don How can I do that?
0
Right, thank you!