In Python, multiple conditions can be checked using ‘and’ or ‘or’ or BOTH in a single if statement.
if(condition1 and/or condition2)and/or(condition3 and/or condition4)...: pass else: pass
- and = this work when both conditions provided with should be true. If the first condition falls false, the compiler doesn’t check the second one. If the first condition is true and the compiler moves to the second and if the second comes out to be false, false is returned to the if statement.
- or = this work when either condition needs to be true. The compiler checks the first condition first and if that turns out to be true, the compiler runs the assigned code and the second condition is not evaluated. If the first condition turns out to be false, the compiler checks the second, if that is true the assigned code runs but if that fails too, false is returned to the if statement.
Example of using and, or in if statements:
# program to find the largest number among # given three numbers a = 4 b = 2 c = 8 if ((a>b and a>c) and (a != b and a != c)): print(a, " is the largest") elif ((b>a and b>c) and (b != a and b != c)): print(b, " is the largest") elif ((c>a and c>b) and (c != a and c != b)): print(c, " is the largest") else: print("numbers are equal")
8 is the largest