Reputation: 669
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
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
Reputation: 2290
!
is not negation in Python; Python just uses words for common booleans:
and
(not &&
)
or
(not ||
)
not
(not !
)
Generally speaking:
len
of the container)None
is falsy__bool__
method with its own custom behaviorUpvotes: 2
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.
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
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