I am stuck about True
/False
of x
and not x
,
for x = 0
where x
is int
, in Python.
Why does if not x
allow execution of the following statement and why not for if x
?
Please give explanation.
I am stuck about True
/False
of x
and not x
,
for x = 0
where x
is int
, in Python.
Why does if not x
allow execution of the following statement and why not for if x
?
Please give explanation.
from the python docs:
"By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object. 1 Here are most of the built-in objects considered false:
constants defined to be false: None
and False
.
zero of any numeric type: 0
, 0.0
, 0j
, Decimal(0)
, Fraction(0, 1)
empty sequences and collections: ''
, ()
, []
, {}
, set()
, range(0)
https://docs.python.org/3/library/stdtypes.html
that is, zero is integer,
>>> type(0)
<class 'int'>
but has a False logical value, as '', (), []... and so on
Because in python 0
is considered false, so when you write (if x)
it will execute only when x !=0
(so it will be evaluated as true).
If statements don't execute their contents if their condition evaluates to a "false" value, like 0, an empty string, False
, or an empty list/tuple.
Going to assume you mean
x = True
y = 0
if x:
print('x is true')
if not y:
print('your not sure why this prints')
This is because in Python, 0
evaluates to False.
0
is a subclass bool, False
, while any number that's not zero evaluates to True
.
x = 0
if not x
is like saying
x = 0
if x is False:
which the condition meets.
Sounds like you need a bit of Boolean review.
Everything in the world of python (and most of programming) boils down to be either True or False.
Lets take Integers, for example.
In python (and probably most languages) a value of 0 goes to False and everything else is True.
You can get the true/false value of just about anything in python by using the bool
function. Try bool(0)
or bool(2)
.
Now, what if
does is take an expression (basically just a Boolean value), and if it is True, executes the code block, and if it's False, skips it.
x = 0
if x:
print("This will never be printed because x is", x, "and it's Boolean value is", bool(x))
Now, what not
does is take a Boolean value and make it the opposite. not True
is False
. not False
is True
. It does that however many times not
is there, so not not True
would be True
.
x = 0
if not x:
print("This will print, because x is", 0, "the Boolean value of x is", bool(x), "and the not value of boolean x is", not bool(x))
Ultimately: because the language definition says so.
Python has chosen to make almost any expression implicitly convertible to a boolean (True/False) value. The conversion is defined in the language.
For integer types, the conversion is that 0 is False, other values are True.
And, of course, if an expression X is False, then not X is True, by simple definition of the operator not.