Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional `try` statement with a "general" exception message

I want to try to load a file if a conditional is true. I want a second (one line) bit of code to execute if either a file exception occurs or the conditional is false.

In order to involve birds, consider the following code:

if try_to_fly:
    try:
        fly()
    except FlyError:
        walk("I'm walking instead of flying.")
else:
    walk("I'm walking stead of flying.")

# more lines below #

This does what I want to do. But, it has the line walk("I'm walking stead of flying.") twice, which would be nice to avoid.

Also, there's more code to do below this bit, so we can't return in the try statement without accounting for that code.

Is there a more pythonic way to do this?

like image 809
Jay Calamari Avatar asked Jun 22 '26 10:06

Jay Calamari


1 Answers

Without using any additional variable:

try:
    if try_to_fly:
        fly()
    else:
        walk("I'm walking stead of flying.")
except FlyError:
    walk("I'm walking instead of flying.")
like image 90
Taohidul Islam Avatar answered Jun 23 '26 23:06

Taohidul Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!