IN Perl it's quite common to do things like function() || alternative()
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.
function() or alternative()
机制完全一样。
try with or
:
>>> def bye():
return 3
>>> print bye() or 342432
3
Unfortunately, this does not work like in Perl, because in Perl, after an assignment like my $c = $d || 45;
my $c = $d || 45;
you have in $c
the value 45 if $d
is undefined. In Python you get an error NameError: name 'd' is not defined
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.