Shorter, more pythonic way of writing an if statement

后端 未结 6 1687
情书的邮戳
情书的邮戳 2021-01-30 08:38

I have this

bc = \'off\'

if c.page == \'blog\':
    bc = \'on\'

print(bc)

Is there a more pythonic (and/or shorter) way of writing this in Pyth

6条回答
  •  醉梦人生
    2021-01-30 09:26

    You could use an inline if statement:

    >>> cpage = 'blog'
    >>> bc = 'on' if cpage == 'blog' else 'off'
    >>> bc
    'on'
    >>> cpage = 'asdf'
    >>> bc = 'on' if cpage == 'blog' else 'off'
    >>> bc
    'off'
    

    There's a bit of a writeup on that feature at this blog, and the relevant PEP is PEP308. The inline if statement was introduced in Python 2.5.

    This one is less pythonic, but you can use and/or in this fashion:

    >>> cpage = 'asdf'
    >>> bc = (cpage == 'blog') and 'on' or 'off'
    >>> bc
    'off'
    >>> cpage = 'blog'
    >>> bc = (cpage == 'blog') and 'on' or 'off'
    >>> bc
    'on'
    

    This one is used more often in lambda statements than on a line by itself, but the form

     A and B or C
    

    is similar to

       if A:
           return B
       else:
           return C
    

    The major caveat to this method (as PEP 308 mentions) is that it returns C when B is false.

提交回复
热议问题