Reputation: 313
How does print(not("0"))
gives a false
as output and print(not())
gives a True
as output?
what does the statement do?
print(not("0"))
print(not())
Upvotes: 0
Views: 2908
Reputation: 115
In Python, empty sequences such as ()
, []
, ''
and {}
all evaluate to False, as well as the interger 0
. You can check this by using the bool() function on any of these values.
In your first print, the not
operator returns the boolean value that is the opposite of the boolean value of ("0")
, which isn't an empty sequence nor 0
. In other words, if you call bool(("0"))
, you will get True
in return, and not True
returns False
.
In your second print, it's exactly the opposite happening. bool(())
is False
, therefore not ()
should be True
.
BTW: In your first print example, the value ("0")
is not a tuple, but a string. I mention this just in case you were thinking otherwise.
Upvotes: 1
Reputation: 449
This is because when you pass 0 as a string to the not function, it considers it as a True value and thus negating it becomes False. Whereas an empty string is considered as False value and thus negating it becomes True. If you pass 0 as a number instead of a string, it will return you True again.
Upvotes: 1
Reputation: 62
Not is very similar to the if condition !=. If a value is truthy, then it returns false. If a value is falsy, it returns true. Since most strings are truthy, it returns false, and since a None value is falsy, it returns true
so for example print(not(True))
would return false and print(not(False))
would return true
Upvotes: 2