Which of `if x:` or `if x! = 0:` is preferred in Python?

Assuming x is an integer, the if x: construct functionally matches if x != 0: in Python. The style guides of some languages ​​explicitly forbid against the first - for example, the ActionScript / Flex style guides say that you should never enter an int for bool for this kind of thing.

Does Python have a preference? A link to PEP or another reputable source is best.

+4
source share
7 answers

Construction: if x: commonly used to check for boolean values.

For int preferable to use explicit x != 0 - for strings of explicit it is better than implicit ( PEP 20 - Zen of Python ).

+7
source

There is no hard and fast rule. Here are some examples where I will use each:

Suppose I interact with some function that returns -1 on error and 0 on success. Such functions are fairly common in C, and they often occur in Python when using a library that wraps C functions. In this case, I would use if x:

On the other hand, if I am going to divide by x , and I want to make sure that x not 0 , then I will be explicit and write if x != 0 .

Generally, if I treat x as a bool in the whole function, then I will probably use if x: - even if I can prove that x will be int . If in the future I decide that I want to pass to the bool function (or some other type!), I will not need to change it.

On the other hand, if I really use x as an int , then I will most likely write 0 .

+2
source

I usually read:

if(x) is a question of existence.

if( x != 0) is the question of number.

+1
source

It depends on what you want; if x is an integer, they are equivalent, but you must write code that matches your exact intention.

 if x: # x is anything that evaluates to a True value if x != 0: # x is anything that is not equal to 0 
+1
source

Can I assume that the number of disputes on this issue is enough to answer it?

Some argue that this “if x” should be used only for Z, others for Y, others for X.

If such a simple statement can create such a fuss, it is clear to me that the statement is not clear enough. Write what you mean.

If you want to check that x is 0, write "if x == 0". If you want to check if x exists, write "if x is not None."

Then there is no confusion, disputes, disputes.

0
source

If you want to check x in a boolean context:

 if x: 

More explicit, for x validity (doesn't match empty containers):

 if x is not None: 

If you want to strictly check in integer context:

 if x != 0: 

This last one is actually implicitly comparing types.

0
source

Wouldn't if x is not 0: preferred method in Python over if x != 0: :?

Yes, the first is a little longer to write, but I got the impression that is and is not preferable == and != . This makes it easier to read Python as a natural language than as a programming language.

-1
source

Source: https://habr.com/ru/post/1315244/


All Articles