Better Way Than Using If-else Statement In Python
Solution 1:
You can do:
s = [1, 2, 3, 4]
print 'y' if len(s) > 5 else 'n'
However I don't think this makes the code more readable (at a glance). Also note that if
and else
don't create a loop, they are simply statements for control flow. Loops are written using for
and while
.
Solution 2:
Short, but very obfuscated (don't do this):
print 'ny'[len(s) > 5]
[edit] the reason you should never do this, is because it uses properties of the language that are little known to most people, i.e. that bool is a subclass of int. In most situations where you find yourself writing code like the OP, it's usually better to create a flag variable
s_is_long = len(s) > 5
then you can use any of the more appropriate ways to write the print, e.g.:
print 'y' if s_is_long else 'n'
or
print {True: 'y', False: 'n'}[s_is_long]
or the most readable of all...
if s_is_long:
print 'y'
else:
print 'n'
Solution 3:
In this case you could use the try/except block:
try:
print s.index(5)
except ValueError:
print "5 not in list"
Solution 4:
Short and clear:
s = [1, 2, 3, 4]
output = {True: 'y',False: 'n'}
print output[len(s) > 5]
Solution 5:
Another variation:
print len(s)>5 and 'y' or 'n'
just added for completness. Don't try this at home! ;-)
Post a Comment for "Better Way Than Using If-else Statement In Python"