Shorter, more pythonic way of writing an if statement

后端 未结 6 1697
情书的邮戳
情书的邮戳 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:19

    Shortest one should be:

    bc = 'on' if c.page=='blog' else 'off'
    

    Generally this might look a bit confusing, so you should only use it when it is clear what it means. Don't use it for big boolean clauses, since it begins to look ugly fast.

提交回复
热议问题