u_ser722345
u_ser722345

Reputation: 669

Are there any pitfalls associated with using !var in python?

I want to check if a variable has a truthy value; in Python does something like this work effectively to check that? Or is there a different convention?

if not var:
  return False
return var * 2

Upvotes: 2

Views: 70

Answers (4)

Mp0int
Mp0int

Reputation: 18737

A small hint about your example. In some cases (like yours) making a if True check is simpler and shorter:

if var:
    return var * 2

Because all functions return a value in python. That is also important about truth testing. If a method or function do not have a return statement, then it returns None Above is equivalent of

if var:
    return var * 2
return None

Upvotes: 0

Free Monica Cellio
Free Monica Cellio

Reputation: 2290

! is not negation in Python; Python just uses words for common booleans:

and (not &&) or (not ||) not (not !)

Generally speaking:

  • For numbers, nonzero values are truthy, while zero is falsy
  • For containers, empty containers are falsy (you can also think of it as being equivalent to the len of the container)
  • None is falsy
  • Any class can define a __bool__ method with its own custom behavior

Upvotes: 2

Andrew Walker
Andrew Walker

Reputation: 42500

The biggest pitfall is that so many things in Python evaluate to a boolean value. The documentation contains a complete list of how (builtin) types can be tested for truth. The following all evaluate to false.

  • None
  • False
  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a
  • nonzero() or len() method, when that method returns the integer zero or bool value False.

To make things easier for yourself, try to restrict the return type of your function to one type and denote exceptional cases with exceptions.

Upvotes: 1

Deelaka
Deelaka

Reputation: 13723

If a variable is True you can check if it is True using the following syntax

>>> x = True
>>> if x:
...     print 'hey'
...     
hey

To check if a variable is False the following syntax could be used:

>>> x = False
>>> if not x:
...     print 'hey'
...     
hey

Note : There is no need to use the bool() function in these cases

Upvotes: 4

Related Questions