How to Use If Statements in Python?

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

Syntax:

`if condition:`

` code`

Example:

`if x > 0:`

` print(“Positive”)`

Use `elif` for additional conditions

Example:

`if x > 0:`

` print(“Positive”)`

`elif x < 0:`

` print(“Negative”)`

Use `else` for the default case

Example:

`if x > 0:`

` print(“Positive”)`

`else:`

` print(“Not positive”)`

Use comparison operators:

`==`

`!=`

`>`

`<`

`>=`

`<=`

Use logical operators:

`and`

`or`

`not`

Combine conditions:

`if x > 0 and x < 10:`

Check membership:

`if item in my_list:`

Check identity:

`if a is b:`

Use indentation to define the code block

Use `pass` when no action is needed

Example:

`if x > 0:`

` pass`

Nest `if` statements when needed

Example:

`if x > 0:`

` if x < 10:`

` print(“Between 1 and 9”)`

Suggested for You

Trending Today