How to do it in a pythonic way?

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
+3
source share
8 answers

Use the operator in:

if a in (7,8,9):
    pass
+17
source

To check if it falls within a range:

if 7 <= a <= 9:
  pass

To check if a is in the given sequence:

if a in [3, 5, 42]:
  pass
+15
source
for a in range(10):
    if a > 6:
        continue
    print('yes')
+2

"pythonic":

if not a in [7, 8, 9]:
     print 'yes'

if a not in [7, 8, 9]:
     print 'yes'

, , "".

+2
if a in [7,8,9]
+1

, , map() :

def _print(x):
    print 'yes'

map(_print, [a for a in range(10) if a not in (7,8,9)])
+1

.

>>> f = lambda x: x not in (7, 8, 9) and print('yes')
>>> f(3)
yes
>>> f(7)
False
+1

, , :

if a == 7:
    pass
if a == 8:
    pass
if a == 9:
   ...
else:
   ...

- if, , -

 if a == 9:

therefore, if a is 7 or 8, the program prints yes. For future use of an if-else statement like this, be sure to use elif:

if a == 7:
    seven()
elif a == 8:
    eight()
elif a == 9:
    nine()
else:
    print "yes"

or use only one if statement if they require the same action:

if a == 7 or a == 8 or a == 9:
    seven_eight_or_nine()
else:
    print "yes"
+1
source

Source: https://habr.com/ru/post/1741068/


All Articles