notjoshno
notjoshno

Reputation: 357

Which conditional statement is more pythonic?

Which of the following would you consider more Pythonic:

return x if not x > 5 or not variable == True else y

or

return x if not (x > 5 and variable == True) else y

Upvotes: 0

Views: 68

Answers (2)

jarhill0
jarhill0

Reputation: 1629

I would write this as

return y if x > 5 and variable else x

The fact that you negate your conditional in the second option makes it easy to switch the if and else parts of this statement.

Also, it is (almost) never a good practice in any language to compare a boolean value to true as in

if variable == True:

Just write

if variable:

Upvotes: 4

Mureinik
Mureinik

Reputation: 311088

Neither is more Pythonic, it's just a question of how you structure your boolean logic. I would, however, replace variable == True with simply variable.

Upvotes: 1

Related Questions