mercredi 27 janvier 2021

Python checks, multiple nested if else statements

I need to run multiple checks that lead to different outcomes before executing the main code.

It looks something like that:

if cond1:
    ...
    if cond2:
        ...
        if cond3:
            ...
            if cond4:
                ...
                # main code here
                ...
            else:
                print('cond4 failed')
        else:
            print('cond3 failed')
    else:
        print('cond2 failed')
else:
    print('cond1 failed')

The ... represents arbitrary parts of code that could be used in future conditions.

As I have multiple checks, the else statements seems pretty disconnected from their condition which makes it hard to see what runs if a particular condition fails. Is there a more readable way to do this?

Aucun commentaire:

Enregistrer un commentaire