assert
is exactly like if
. It is a keyword, followed by an boolean expression, and it requires the expression to evaluate to True
. The statement assert expression
will succeed if and only if the if expression
succeeds.
Given that, there are two aspects to your questions. The first condition
vs condition==True
. This is a matter of style. You don't write if condition==True:
, but simply if condition:
. Similarly, there is no reason to write
assert is_even(6) == True
Just write
assert is_even(6)
instead.
The second is condition==True
vs condition is True
. This is not a matter of style only. Run the following
if []==False: # also: if not []
print('false')
if bool([]) is False:
print('false')
if [] is False:
print('false')
Examples (1) and (2) will print, but example (3) will not.
False
is a singleton value, meaning that there is only one False
object in the python interpreter, and all false objects are the same object. So, using is
feels right (just like it is considered good style to write if object is None
). However, there is the concept of falsy/truthy values in python: if condition
does not necessarily trigger if condition
is false, but if bool(condition)
is false. That's done automatically. In the example above, the empty list is a falsy value. That is bool([])
evaluates to the False
object (which, again, is only one). So, example (1) succeeds, because it is automatically converted (internally) to something like example (2). However, example (3) does not work, because, although an empty list evaluates to false, it is not False
. It is an empty list. So, to sum up you example
if greeting: # good style, and it works
if greeting==True: # bad style, redundant, but it still works
if greeting is True: # misleading. does a different thing than it seems to do. avoid it
Closing comment: you give the example
def is_even(number):
if number % 2 == 0:
return <>
else:
return False
where you mention that <>
could be any truthy value. In that spirit, it would be equivalent to write
def is_even(number):
return number % 2
since it would return non-zero (truthy) or zero (falsy). However, don't do that. A user of a function called is_even
would expect the function to return True
or False
, not an integer. You don't know how that user is using your code (eg. might send it to a database, or web service that expects a really boolean value). So it would be better to return a boolean value. So, the shortest and safest form of the function would be to write
def is_even(number):
return bool(number % 2)