As I have started learning Python recently, I came across this boolean concept and I execute this expression bool("0"), but I got a confusing result as True of this expression, can anybody tell me why this happens.
bool("0") evaluates to True because"0" in this case is a non-empty string. It's useful for things like :
if str: #check if str is not empty
#do something
bool(0) on the other hand evaluates to False.
It is because it will return True for every non-empty strings,lists,etc.
If int type varieble is zero Interpreter shows it as False .bool("0") evaluates to True because"0" in this case is a non-empty string,NOT intSee it full in one photo
Related
a=True and 1/0
print(a)
The output for the above code fragment shows an error.
While the output for the below code fragment :
a=False and 1/0
print(a)
Is False
Why is that so? From the layman point of view, since 1/0 is undefined, error should be displayed in each case.
Similarly if I take a = True or 1/0, output is true while an error for False or 1/0
I tried different versions of this:
a=1/0 or False
print(a)
or
a=1/0 or True
print(a)
Both of which display an error (division by zero)
I realized that it has something to do with the order I take them in and the boolean operators I use.
In any case, why am I getting an output and in some cases?
Both and and or are short circuited i.e. if the first input is respectively false or true, the rest of the inputs are not evaluated at all. That is why both False and 1/0 as well as True or 1/0 can return results, while other variations do not.
Python exhibits short-circuit evaluation semantics for and and or expressions. What that means is that, if the result of the entire expression can be determined from the left-hand-side, then the right-hand-side needn't be evaluated.
False and a
Here, we first evaluate the expression False (which is a literal and equal to the Python value False). Now, and is only true if both sides are true, and we've already found one side which is false. So no matter what a evaluates to, the result is False. Hence, we don't evaluate the right-hand-side because it's unnecessary.
Likewise,
True or a
Since True is truthy and or only requires one of its arguments to be truthy, whatever a evaluates to, the result is True.
This is commonly used to do several veins of error checking in one line. Python doesn't have a null-safe access operator, so we can do the next best thing.
if person is not None and person.salary is not None:
...
Without short-circuit evaluation, the person.salary is not None would evaluate, even in the case where person is actually None, which is an error. We'd have to write the more verbose
if person is not None:
if person.salary is not None:
...
which does nothing for readability.
Likewise, we can use or to short circuit error conditions.
if person is None or person.salary is None:
raise(MyCustomException("This person doesn't have a job"))
Again, if person happens to be None, we don't want person.salary to evaluate at all, or we'll get an AttributeError rather than our nice, informative custom exception. Without short-circuiting, we'd have to resort to the much uglier
if person is None:
raise(MyCustomException("This person doesn't have a job"))
if person.salary is None:
raise(MyCustomException("This person doesn't have a job"))
In case of False, It is not necessary to check more after and - it is due to the optimization, so 1/0 is never executed.
On the other hand: a=1/0 and False will not work as 1/0 is evaluated first.
and operator stops when a False is encountered to save resources.
Here:
a=False and 1/0
Division is never computed.
The same you can check with or operator: it stops when True is validated:
a=True or 1/0
Will give True.
I have a two-line code like this:
if validated_data.get('is_shipped') == False: # 管理员取消了发货,则把物流信息删掉
validated_data.update(logistics_company=None, logistics_tracking_no=None)
I am using Pycharm and the PEP8 check is on. So there is an underline below validated_data.get('is_shipped') == False which shows me Expression can be simplified. Replace boolean expression with ``not validated_data.get('is_shipped')`` . But, the truth is, I only want to run code in if statement when is_shipped is explicitly passed as False, and not when is_shipped is None. So, how can I handle this PEP8 check warning?
You hit the solution in your question: use the explicit is operator:
if validated_data.get('is_shipped') is False:
This makes your condition an explicit identity, rather than the "truthy" boolean evaluation.
Here x == False is equivalent to not x, and I don't know why do you want to only use x == False and PEP8 suggests that:
if not validated_data.get('is_shipped'): # 管理员取消了发货,则把物流信息删掉
validated_data.update(logistics_company=None, logistics_tracking_no=None)
I think I just witnessed something really scary and hard to digest!
So in my projects I came across this beautiful piece of code
from CoreDefaults import FALSE, TRUE
After looking into the CoreDefaults module I saw this
TRUE = 1 == 1 # some part of my mind was blown here
FALSE = 0 == 1 # which I honestly thought was clever and it really is!
But then it raised a question that when python gives default True and False why would anyone evaluate the value of True and False and then assign to such variables but then I got a hunch that the only reason anyone would do was if those values can be reassigned!
So I tried the following
>>> True
True
>>> False
False
>>> True = False # True is assigned to False and it is NOT OK ?
>>> True
False # Python, I think it's over between you and me.
Is this behavior normal ? Is this the way it's supposed to be implemented ? Why not make it non-editable ? Is this a security risk when using python or is it the same with other languages too ? Any clever way of making it more non-editable like any builtin I need to override ? How do I fall asleep tonight ?
I'm using python 2.6.6.
EDIT 1 :
So can we use 0 and 1 instead of False and True instead ? I think it's more fail proof though ?
In Python 2, True and False are builtin "constants". You are quite right about it not being safe. But Python doesn't actually have constants, so to make it impossible to assign a different value, they need to be keywords. True and False are keywords in Python 3. But it would have been disruptive to add these new keywords to Python 2.
BoarGules answer is mostly correct but incomplete. The built-in bool type and built-in False and True were add in one of the 2.2.z releases. (This was before the 'no new features in maintenance releases' rule. Indeed, the confusion engendered by the mid-version addition is one of the reasons for the rule.)
Before this addition, people who wanted to use False and True had to write something like the following near the top of their code.
False, True = 0, 1
Making False and True uneditable keywords would have broken existing code. That would indeed have been distruptive. After the addition, people could optionally edit their code to
try:
False
except NameError:
False, True = 0, 1
in order, when running with newer 2.x releases, to have False and True be bools, and print as 'False' and 'True' instead ints printing as 0 and 1.
In 3.0, when most people had dropped support for 2.2 and before, and hence no longer needed the assignment alternative, False and True were made keywords.
I'm using Code Academy and I began with Python. For the "Grand Finale" of Conditionals and Control Flow and this is the problem:
"Write an if statement in the_flying_circus(). It must include:
if, elif, and else statements;
At least one of and, or, or not;
A comparator (==, !=, <, <=, >, or >=);
Finally, the_flying_circus() must return True when evaluated.
Don't forget to include a : after your if statements!"
and I know this is the format:
def the_flying_circus():
if condition:
# Do Something!
elif condition:
# Do Something Else!
else condition:
# Do yet another thing!
Firstly, I don't know what exactly it means by conditions. I thought it meant condition using comparators in relation to the_flying_circus, but that showed an error message. Am I supposed to define the_flying_circus? If not is it already defined, and how would I know the definition? It says it's an invalid syntax error. Secondly, with the "#Do Something" I think I'm supposed to use strings, so a certain script shows up if the_flying_circus fulfills one of the 3 certain conditions, but since I can't figure out what to write for the conditions I don't know. Also, Code Academy did give an overview of if, elif and else statements, but I'm still shaky on the concept. An overview with a simplified example of what this would be used for in real life would be greatly appreciated.
In all languages a condition is some expression that can evaluate to a boolean expression i.e 1<2 or anything else so lets take a look at the following code
def the_flying_circus():
x = True
if True and x:
print "x is true"
if 2 < 1:
print "The universe is ending"
elif 2>1:
print "Ok sanity"
else:
print "the sky is falling"
return True
So each conditional statement checks whether or not a condition is true, and evaluates the following statement at the end. Lastly return True so the method condition is satisfied.
Something like
def the_flying_circus():
if 1>2 or 2==3:
return False
elif 4<3:
return False
else:
return True
You are defining the_flying_circus as a function. It uses > == and < as comparators. It has if, elif, and else. It returns True.
The conditions are the things that could be true or false but have to be checked by the if/elif statement. "4<3" is a condition. It evaluates to false.
The "#Do something" comments could be anything. Print something, return something, call some other function, etcetera.
Maybe some kind of beginner's tutorial on if statements? Plenty through google.
Consider a simple if/else block in Python like the one below:
if x:
print 'True'
else:
print 'False'
Where x could be a comparison, a condition or simply a string/list/object. How can I open a python shell and find out what if x would evaluate to without writing the loop? i.e. is x True or False for a certain corner case value.
For example, if x is an empty list. Can I open python shell, assign x = [] and then write print <function of x> that'll output True or False on execution. What is that <function of x>?
I feel I'm asking a rather silly question and can't think straight right now but I often find myself opening a shell, assign a corner case value to a variable and write an if/else to see what corner values would evaluate to True/False. I'm just looking for a shorter way to find out on the shell, without writing the 4-line loop.
You are looking for the function bool.
>>> bool([])
False
>>> bool(['monty'])
True
What the Python Docs say.
Convert a value to a Boolean, using the standard truth testing
procedure. If x is false or omitted, this returns False; otherwise it
returns True. bool is also a class, which is a subclass of int. Class
bool cannot be subclassed further. Its only instances are False and
True.
Your four lines should be the same as
print(bool(x))