Is it bad practice to use the following format when my_var
can be None?
if my_var and 'something' in my_var: #do something
The issue is that 'something' in my_var
will throw a TypeError if my_var is None.
Or should I use:
if my_var: if 'something' in my_var: #do something
or
try: if 'something' in my_var: #do something except TypeError: pass
To rephrase the question, which of the above is the best practice in Python (if any)?
Alternatives are welcome!
Yes, the order of the conditions matters. In your code, you test if(a==b) first. If all 3 integers are the same, then this will be true and only return c; will execute. It won't even bother with the rest of the conditions.
The block of code inside the if statement is executed is the condition evaluates to true. However, the code inside the curly braces is skipped if the condition evaluates to false, and the code after the if statement is executed.
You always place the condition to be evaluated by JAWS between the If and Then key words. JAWS evaluates this condition to determine what statements should be performed next. When the condition is found to be true, then JAWS performs all statements following the If statement.
The evaluation order is specified by the standard and is left-to-right . The left-most expression will always be evaluated first with the && clause.
It's safe to depend on the order of conditionals (Python reference here), specifically because of the problem you point out - it's very useful to be able to short-circuit evaluation that could cause problems in a string of conditionals.
This sort of code pops up in most languages:
IF exists(variable) AND variable.doSomething() THEN ...
Yes it is safe, it's explicitly and very clearly defined in the language reference:
The expression
x and y
first evaluatesx
; ifx
isfalse
, its value is returned; otherwise,y
is evaluated and the resulting value is returned.The expression
x or y
first evaluatesx
; ifx
is true, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With