I wrote some code with a lot of 'if..elif' statements in Python. I know the code style may be considered bad and I want to improve it.
num = int(input('please input a number: '))
if num <= 0:
print('1')
elif 0 < num <= 5:
print('2')
elif 5 < num <= 10:
print('3')
elif 10 < num <= 15:
print('4')
elif 15 < num <= 20:
print('5')
elif 20 < num <= 25:
print('6')
I would like to know how to replace so many 'if..elif' statements with other solutions?
Take Advantage of the Boolean Values. There's no need to have the if/else statements. Instead, we can use the boolean values. In Python, True is equal to one , and False is equal to zero .
The elif statement in Python If you have multiple conditions to check and for each condition different code is required to execute, you may use the elif statement of Python. The elif statement also takes an expression which is checked after the first if statement. You may use multiple elif statements.
one elif statement can be there. If the condition is false, the else statement will be executed.
You could do something like this:
print(((num - 1) // 5) + 2)
Example when num
is 20:
((num - 1) // 5) + 2
((20 - 1) // 5) + 2
(19 // 5) + 2
3 + 2
5
In the general case... not sure. If you're talking about a completely arbitrary if-elif-else construct, then I would say no, at least not in a way that would help readability. In fact, the answer I just gave you for your specific example might not even help readability, so I'm not sure how well you can hope for that in the general case.
For simple examples like this where the different cases fit a clear pattern, the best thing would be something like what RedRoboHood suggested where you remove the conditional altogether (modified slightly to support lower bound), e.g.
print('%s' % max((num - 1) // 5 + 2, 1))
If you want to be slightly more general and allow print statements that do not follow a pattern with the input, you could use a python dictionary:
# what to print if num is less than the number but greater than the previous
mapping = {0:'1', 5:'2', 10:'3', 15:'4', 20:'5', 25:'6'}
# clamp the number to the upper bound of the desired range
clamped_num = 5 * max((num - 1) // 5, -1) + 5
print(mapping[clamped_num] if clamped_num in mapping else 'Bad value')
However, there will always be times where you cannot boil it down like this, and for those I think if-else statements are fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With