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
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.