IN Perl it's quite common to do things like function() || alternative()
. If the first returns false it will run the second one.
How can this be easily implemented in Python?
Update
Examples (pseudocode):
x = func() or raise exeption
x = func() or print(x)
func() or print something
If possible solutions should work with Python 2.5+
Note: There is an implied assumption that you cannot modify the func() to raise exceptions, nor to write wrappers.
Use or
: Python uses short circuit evaluation for boolean expressions:
function() or alternative()
If function
returs True, the final value of this expression is determined and
alternative
is not evaluated at all.
you can use or
:
function() or alternative()
also, there is conditional expression defined in PEP 308:
x = 5 if condition() else 0
Which is sometimes useful in expressions and bit more readable.
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