0

I want to do an inline check to see if an object exists or is None.

Coming from LUA I'm used to writing print user and 'logged in' or 'not logged in'.

However when searching the web, I can't find this method anywhere. Instead people advice you to use print 'logged in' if user else 'not logged in'.

Both methods work though, is there a reason why I shouldn't use print var and 'yes' or 'no'?

  • 1
    Because readability counts – vaultah May 18 '15 at 15:11
  • http://stackoverflow.com/questions/11880430/how-to-write-inline-if-statement-for-print – Sterling Archer May 18 '15 at 15:11
  • 1
    https://www.python.org/dev/peps/pep-0008/ https://www.python.org/dev/peps/pep-0020/ – Łukasz Rogalski May 18 '15 at 15:13
  • Readability is exactly the reason why I prefer the first method. Also, could you elaborate why you're posting that question @Sterling Archer? That's one of the reasons I've written this question – Bassdrop Cumberwubwubwub May 18 '15 at 15:13
  • Here, another "readable" version `print(['logged in', 'not logged in'][not user])` – vaultah May 18 '15 at 15:15
  • 2
    The conditional expression syntax is always preferable. It was added to avoid common pitfalls with the `and` / `or` syntax ([*The motivating use case was the prevalance of error-prone attempts to achieve the same effect using "and" and "or".*](https://www.python.org/dev/peps/pep-0308/). – Martijn Pieters May 18 '15 at 15:17
  • @Martijn Pieters Thanks, that's what I was looking for. *In my opinion though,* this should be an answer. This question is not a duplicate for I am not asking whether such operator exists and the linked question does not implicitly answer my question. – Bassdrop Cumberwubwubwub May 18 '15 at 15:27
  • @Bas: it was that or closing as primarily opinion based. I think there are other dupes but the `and` and `or` syntax make this hard to search for. – Martijn Pieters May 18 '15 at 15:28
  • @Bas: [Is this idiom pythonic? (someBool and "True Result" or "False Result")](https://stackoverflow.com/q/345745) might be a better target, in that context. – Martijn Pieters May 18 '15 at 15:30
  • @MartijnPieters Much better indeed. Searching for a similar question did not yield any results, probably because I wasn't using the right search-terms. Thanks again – Bassdrop Cumberwubwubwub May 18 '15 at 15:33

0 Answers0