Python If Statements Explained With Examples

The if statement is a fundamental element of Python's control flow, allowing developers to make decisions based on conditions.

In this guide, we'll explore the syntax of the if statement and provide examples to illustrate how it is used in Python.

Anatomy of the if Statement:

The basic structure of an if statement in Python is as follows:

if condition:
    # Code to execute if the condition is True

The code block following the if statement is indented and executed only if the specified condition evaluates to True.

Example 1: Checking a Condition

Let's consider a simple example where we check if a variable x is greater than 10:

x = 15

if x > 10:
    print("x is greater than 10")

In this example, the condition x > 10 is True, so the indented code block is executed, resulting in the output: x is greater than 10.

Example 2: Handling Multiple Conditions with elif and else

You can extend the if statement to handle multiple conditions using elif (short for "else if") and else. In this example, we'll classify a number into different categories:

number = 7

if number > 0:
    print("Number is positive")
elif number == 0:
    print("Number is zero")
    print("Number is negative")

Depending on the value of number, one of the three code blocks will be executed.

Example 3: Nested if Statements

You can nest if statements to handle more complex logic. Here's an example that checks both the value and the parity of a number:

num = 12

if num > 0:
    print("Number is positive")

    if num % 2 == 0:
        print("Number is even")
        print("Number is odd")

    print("Number is not positive")

In this nested example, the outer if statement checks if the number is positive. If true, it then checks whether the number is even or odd within the nested if statement.

Example 4: Ternary Conditional Operator

Python supports a concise ternary conditional operator for inline if statements. It provides a compact way to express simple conditional assignments:

value = 15

result = "Greater than 10" if value > 10 else "Less than or equal to 10"

In this example, the value of result is assigned based on the condition.


Understanding and mastering the if statement is crucial for writing dynamic and responsive Python programs.

Whether you're making simple comparisons or handling complex nested conditions, the if statement empowers you to control the flow of your code.

Experiment with these examples, and as you become more comfortable with if statements, you'll gain a valuable tool for building sophisticated and logic-driven applications in Python.