Home > Mobile >  Python remove try inside except?
Python remove try inside except?

Time:03-25

In python I have a function called func() which could raise NoSuchElementException: I'm trying to call it with input1 if not correct call it with input2 else give up.

Is there any better way to write this code for clarity:

submit_button = None
try:
    submit_button = func(input1)
except NoSuchElementException:
    try:
        submit_button = func(input2)
    except NoSuchElementException:
        pass

CodePudding user response:

you can do something like:

for i in [input1, input2]:
    try:
        submit_button = func(i)
        break
    except NoSuchElementException:
        print(f"Input {i} failed")
else:
    print("None of the options worked")

If the first input doesn't throw an exception you break the loop, otherwise you keep in the loop and try the second input.

This way you can try as many inputs as you want, just add them into the list

The else at the end executes if you never broke the loop, which means none of the options worked

This works well if you want to try several inputs and treat them equally. For only two inputs your code looks readable enough to me. (try this, if it doesn't work try that)

  • Related