samedi 23 juin 2018

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?

Aucun commentaire:

Enregistrer un commentaire