Consider this Python snippet:
for a in range(10):
if a == 7:
pass
if a == 8:
pass
if a == 9:
pass
else:
print "yes"
How can it be written shorter?
#Like this or...
if a ?????[7,8,9]:
pass
Consider this Python snippet:
for a in range(10):
if a == 7:
pass
if a == 8:
pass
if a == 9:
pass
else:
print "yes"
How can it be written shorter?
#Like this or...
if a ?????[7,8,9]:
pass
To test if a falls within a range:
if 7 <= a <= 9:
pass
To test if a is in a given sequence:
if a in [3, 5, 42]:
pass
Depending on what you want to do, the map()
function can also be interesting:
def _print(x):
print 'yes'
map(_print, [a for a in range(10) if a not in (7,8,9)])
What about using lambda.
>>> f = lambda x: x not in (7, 8, 9) and print('yes')
>>> f(3)
yes
>>> f(7)
False
Since the question is tagged as beginner, I'm going to add some basic if-statement advice:
if a == 7: pass if a == 8: pass if a == 9: ... else: ...
are three independent if statements and the first two have no effect, the else refers only to
if a == 9:
so if a is 7 or 8, the program prints "yes". For future use of if-else statement like this, make sure to use elif:
if a == 7:
seven()
elif a == 8:
eight()
elif a == 9:
nine()
else:
print "yes"
or use just one if-statement if they call for the same action:
if a == 7 or a == 8 or a == 9:
seven_eight_or_nine()
else:
print "yes"
Based on your original code the direct "pythonic" replacement is:
if not a in [7, 8, 9]:
print 'yes'
or
if a not in [7, 8, 9]:
print 'yes'
The latter reads a little better, so I guess it's a bit more "pythonic".