How to use multiple conditions in one if statement in Python?

PythonProgramming

You can use a combination of conditions in an if statement. All your conditions need to be defined using some sort of logic. For example, to check if a number is divisible by both 3 and 5, you can use −

Example

a = 15
if a % 3 == 0:
   if a % 5 == 0:
      print("Divisible by both")

Output

This will give the output −

Divisible by both

Example

You can convert it to a single if using the and operator −

a = 15
if a % 3 == 0 and a % 5 == 0:
   print("Divisible by both")

Example

This will give the output −

Divisible by both

There are other operators like or, not, etc that you can use to build more complex logic.

raja
Published on 19-Apr-2018 12:43:53
Advertisements