There's no hard and fast rule here. Here are some examples where I would use each:
Suppose that I'm interfacing to some function that returns -1 on error and 0 on success. Such functions are pretty common in C, and they crop up in Python frequently when using a library that wraps C functions. In that case, I'd use if x:
.
On the other hand, if I'm about to divide by x
and I want to make sure that x
isn't 0
, then I'm going to be explicit and write if x != 0
.
As a rough rule of thumb, if I treat x
as a bool
throughout a function, then I'm likely to use if x:
-- even if I can prove that x
will be an int
. If in the future I decide I want to pass a bool
(or some other type!) to the function, I wouldn't need to modify it.
On the other hand, if I'm genuinely using x
like an int
, then I'm likely to spell out the 0
.