How to Use IF Condition in Python?

Use `if` to run code only when a condition is `True`

Syntax:

`if condition:`

` statement`

Example:

`x = 10`

`if x > 5:`

` print(“x is greater than 5”)`

Use `elif` for additional conditions

Example:

`if x > 10:`

` print(“x is greater than 10”)`

`elif x == 10:`

` print(“x is 10”)`

Use `else` for the default case

Example:

`if x > 10:`

` print(“x is greater than 10”)`

`else:`

` print(“x is 10 or less”)`

Use comparison operators:

`==`

`!=`

`>`

`<`

`>=`

`<=`

Use logical operators:

`and`

`or`

`not`

Example with `and`:

`if x > 5 and x < 15:`

` print(“x is between 5 and 15”)`

Example with `or`:

`if x < 5 or x > 15:`

` print(“x is outside the range”)`

Example with `not`:

`if not x == 10:`

` print(“x is not 10”)`

Use indentation to define the code block

Use nested `if` statements when needed

Example:

`if x > 0:`

` if x % 2 == 0:`

` print(“positive even number”)`

Suggested for You

Trending Today