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)
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 can't use if statements and loops in my assignment so I was wondering how I would rewrite this line:
if (not float(gravity).is_integer()):
It's just checking to see whether or not gravity is a float or integer so it can pass more code.
My guess is that the assignment is trying to teach you a paradigm of "Ask forgiveness not permission".
In that case:
try:
gravity = float(gravity)
# Do floaty gravity stuff
except (TypeError, ValueError):
gravity = some_default_value_you_can_handle_some_other_way
You can use shortcut operators to achieve logical flow without an if statement.
E.g.
float(gravity).is_integer() and do_stuff()
The second part will only execute if the first part is true.
Alternatively you can use
float(gravity).is_integer() or do_stuff()
where the second part will only execute if the first part is false.
UPDATE
I just read the comment about how the function is simply meant to evaluate if two sides yield an integer hypotenuse. So unless I misunderstood what you're after here, in that case, the whole point is that you don't need an if statement to decide whether you should then explicitly return True or False by yourself; you can simply return the output of the evaluation of is_integer() directly, since this will evaluate to either True or False anyway.
You could use assert in combination with a try block:
try:
assert(not float(gravity).is_integer())
print("evaluated to true")
except:
print("evaluated to false")
Replace the print statements with the code you want to execute in case it evaluates to true or false.
I have a working conditional statement:
if True:
pass
else:
continue
that I would like to turn it into a ternary expression:
pass if True else continue
However, Python does not allow this. Can anyone help?
Thanks!
pass and continue are a statements, and cannot be used within ternary operator, since the operator expects expressions, not statements. Statements don't evaluate to values in Python.
Nevertheless, you can still shorten the condition you brought like this:
if False: continue
Point 1: Are your sure your condition is right? Because if True will always be True and code will never go to else block.
Point 2: pass and continue are not expressions or values, but a action instead You can not use these is one line. Instead if you use, 3 if x else 4 <-- it will work
Ternary expression are used to compute values; neither pass nor continue are values.
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))