user6571608
user6571608

Reputation:

If statement with multiple conditions but only check others if first fails

I'm trying to test two conditions, but only want to check the second condition if the first one fails. One example could be:

if df is None or len(df) == 0:
     # do something

I know I can use two seperate if statements or a try...except block. However, I want to know if there is a more elegant pythonic way of doing it or is two seperate if statements the only way.

Upvotes: 0

Views: 1613

Answers (2)

rambalachandran
rambalachandran

Reputation: 2201

or is a short-circuit operator in python 3. This means the second condition (here len(df) == 0) is executed only if the first one (here df is None) is false.

Upvotes: 2

Swastik Kakran
Swastik Kakran

Reputation: 1

You can running your code like this:

if df == none:
    # Do this

elif len(df) == 0:
    # Do this

else:
    # Do this

It works fine and can definately help

Upvotes: 0

Related Questions