Python if...else Statement


Control flow is one of the most important aspects of programming. In Python, the if...else statement is a fundamental way to control the flow of your program. It allows you to execute certain blocks of code based on whether a condition is True or False.

In this blog post, we will dive deep into the if...else statement in Python, explain its syntax, and provide practical examples to help you understand how it works.


What is the if...else Statement in Python?

The if...else statement in Python allows you to test a condition and perform specific actions based on whether the condition evaluates to True or False. If the condition is True, the code inside the if block is executed. Otherwise, the code inside the else block is executed.

Basic Syntax:

if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False

The Structure of the if...else Statement

The basic structure of an if...else statement is simple. Let’s break it down:

1. The if Block

The if block is executed when the condition evaluates to True.

2. The else Block

The else block is executed when the condition evaluates to False. The else part is optional, and you can use it when you want to specify what happens when the condition is False.


Example of an if...else Statement

Here’s an example to demonstrate the basic usage of an if...else statement:

Example 1: Checking if a number is positive or negative

# Example of if...else
num = -5

if num >= 0:
    print("The number is positive or zero.")
else:
    print("The number is negative.")

Output:

The number is negative.

In this example:

  • If the value of num is greater than or equal to zero, the program prints "The number is positive or zero."
  • Otherwise, it prints "The number is negative."

elif: Adding Multiple Conditions

In Python, you can use elif (short for "else if") to check multiple conditions in sequence. This is useful when you need to test more than two possibilities.

Syntax of if...elif...else:

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition2 is True
else:
    # Code to execute if neither condition1 nor condition2 is True

Example 2: Grading System

Let’s write a program to assign a grade based on a student’s score using if...elif...else.

# Example of if...elif...else
score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

Output:

Grade: B

In this example:

  • If the score is 90 or above, the grade will be "A".
  • If the score is between 80 and 89, the grade will be "B", and so on.

Nested if...else Statements

Sometimes you may need to check multiple conditions within each block of the if...else structure. This can be done using nested if...else statements.

Example 3: Checking a Number’s Parity and Value

# Example of Nested if...else
num = 8

if num >= 0:
    if num % 2 == 0:
        print(f"{num} is a positive even number.")
    else:
        print(f"{num} is a positive odd number.")
else:
    print(f"{num} is a negative number.")

Output:

8 is a positive even number.

In this example:

  • The program first checks if the number is positive (num >= 0).
  • If the number is positive, it checks whether the number is even or odd using the modulus operator %.
  • If the number is negative, it simply prints that it’s a negative number.

Short-circuiting with and and or

You can combine multiple conditions in a single if statement using logical operators like and and or. Python uses short-circuit evaluation, meaning it stops evaluating conditions as soon as the result is determined.

Example 4: Checking Multiple Conditions with and and or

# Example of logical operators in if...else
age = 25
has_license = True

if age >= 18 and has_license:
    print("You are eligible to drive.")
else:
    print("You are not eligible to drive.")

Output:

You are eligible to drive.

In this example:

  • The program checks if the person is 18 or older and has a driving license.
  • Both conditions need to be True for the program to print "You are eligible to drive."

Ternary Operator (Conditional Expressions)

Python also provides a compact way to write simple if...else statements using the ternary operator. This allows you to assign values based on a condition in a single line of code.

Syntax:

value_if_true if condition else value_if_false

Example 5: Ternary Operator for Age Check

# Example of Ternary Operator
age = 18
message = "You are an adult." if age >= 18 else "You are a minor."
print(message)

Output:

You are an adult.

In this example:

  • The ternary operator checks if age is greater than or equal to 18 and assigns the corresponding message accordingly.