if else in Python: Conditional Statements Guide

Master Python if else statements with clear examples. Learn syntax, best practices, and common use cases. Includes interactive code examples and tutorials.

The if else statement in Python provides two-way decision making by executing one block of code when a condition is true and another block when the condition is false. Unlike a simple if statement that does nothing when the condition is false, if else ensures that one of the two code paths will always execute. This makes it essential for creating programs that need to handle both success and failure scenarios.

Basic if else Syntax

The if else statement extends the basic if statement by adding an alternative action when the condition evaluates to False.

if condition:
    # code to execute if condition is True
    statement1
else:
    # code to execute if condition is False
    statement2

The else keyword catches anything that isn't caught by the if condition, acting as a "catch-all" for scenarios not covered by the if statement. Python uses a colon (:) after both the if and else keywords, followed by indented code blocks.

Example 1: Simple if else Statement

a = 200
b = 33

if b > a:
    print("b is greater than a")
else:
    print("b is not greater than a")
Output:
b is not greater than a

Since 33 is not greater than 200, the condition is false, so the else block executes.

How if else Works

The if else statement follows a straightforward execution flow:

  1. Python evaluates the condition after the <code>if</code> keyword
  2. If the condition is <code>True</code>, the first indented block executes and the <code>else</code> block is skipped
  3. If the condition is <code>False</code>, the first block is skipped and the <code>else</code> block executes
  4. After either block completes, execution continues with code after the entire <code>if else</code> structure

Example: Temperature Check

temperature = 15

if temperature > 20:
    print("It's warm outside")
else:
    print("It's cool outside")

print("Have a nice day!")
Output:
It's cool outside
Have a nice day!

The final print statement executes regardless of which branch was taken.

Comparing Values with if else

The if else statement commonly uses comparison operators to make decisions based on numeric or string values.

Example 1: Number Comparison

number = 7

if number % 2 == 0:
    print("The number is even")
else:
    print("The number is odd")
Output:
The number is odd

Example 2: String Comparison

username = "admin"

if username == "admin":
    print("Welcome, Administrator!")
else:
    print("Welcome, User!")
Output:
Welcome, Administrator!

Example 3: Age Verification

age = 16

if age >= 18:
    print("You are eligible to vote")
else:
    print("You are not eligible to vote yet")
Output:
You are not eligible to vote yet

Multiple Statements in if else Blocks

Both the if and else blocks can contain multiple statements, as long as they maintain consistent indentation.

Example:

score = 85

if score >= 90:
    print("Excellent performance!")
    print("You earned an A grade")
    grade = "A"
    bonus_points = 10
else:
    print("Good effort!")
    print("Keep working hard")
    grade = "B"
    bonus_points = 5

print(f"Your grade is: {grade}")
print(f"Bonus points: {bonus_points}")
Output:
Good effort!
Keep working hard
Your grade is: B
Bonus points: 5

One-Line if else (Ternary Operator)

For simple conditions with single statements, Python allows you to write if else on one line, creating more concise code.

Standard Format:

age = 20

if age >= 18:
    status = "adult"
else:
    status = "minor"

print(status)

One-Line Format (Ternary Operator):

age = 20
status = "adult" if age >= 18 else "minor"
print(status)
Output:
adult

More Examples:

# Example 1: Maximum of two numbers
a = 10
b = 20
max_value = a if a > b else b
print(f"Maximum: {max_value}")  # Output: Maximum: 20

# Example 2: Pass/Fail determination
marks = 75
result = "Pass" if marks >= 50 else "Fail"
print(result)  # Output: Pass

# Example 3: Sign determination
number = -5
sign = "Positive" if number > 0 else "Non-positive"
print(sign)  # Output: Non-positive

This compact syntax is particularly useful for simple assignments and quick conditions.

Combining Conditions with Logical Operators

You can use and, or, and not operators to create complex conditions in if else statements.

Example 1: Using <code>and</code> Operator

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive")
else:
    print("You cannot drive")
Output:
You can drive

Example 2: Using <code>or</code> Operator

day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")
else:
    print("It's a weekday")
Output:
It's the weekend!

Example 3: Using <code>not</code> Operator

is_raining = False

if not is_raining:
    print("You don't need an umbrella")
else:
    print("Take an umbrella")
Output:
You don't need an umbrella

Example 4: Temperature Range Check

temperature = 35

if temperature > 30 and temperature < 40:
    print("It's a hot day!")
else:
    print("Temperature is moderate")
Output:
It's a hot day!

Nested if else Statements

You can place if else statements inside other if else statements to handle multiple levels of decision making.

Example 1: Basic Nesting

number = 10

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

Example 2: Grade Classification with Nesting

marks = 85

if marks >= 50:
    print("You passed!")
    if marks >= 90:
        print("Grade: A - Excellent!")
    else:
        print("Grade: B - Good job!")
else:
    print("You failed")
    print("Please retake the exam")
Output:
You passed!
Grade: B - Good job!

Example 3: Multi-Level User Authentication

username = "admin"
password = "secret123"

if username == "admin":
    if password == "secret123":
        print("Access granted")
        print("Welcome to admin panel")
    else:
        print("Incorrect password")
else:
    print("User not found")
Output:
Access granted
Welcome to admin panel

While nesting is powerful, excessive nesting can make code harder to read—consider using elif for cleaner multi-condition logic.

Validating User Input with if else

The if else statement is essential for input validation and error handling.

Example 1: Empty String Check

username = ""

if len(username) > 0:
    print(f"Welcome, {username}!")
else:
    print("Error: Username cannot be empty")
Output:
Error: Username cannot be empty

Example 2: Password Length Validation

password = "abc"

if len(password) >= 8:
    print("Password is valid")
else:
    print("Password must be at least 8 characters")
Output:
Password must be at least 8 characters

Example 3: Numeric Range Validation

age = 150

if age > 0 and age <= 120:
    print(f"Age {age} is valid")
else:
    print("Invalid age entered")
Output:
Invalid age entered

Example 4: List Membership Check

allowed_users = ["alice", "bob", "charlie"]
current_user = "david"

if current_user in allowed_users:
    print("Access granted")
else:
    print("Access denied")
Output:
Access denied

Extending with elif

While this page focuses on if else, you can add elif (else if) between if and else to test multiple conditions sequentially.

temperature = 22

if temperature > 30:
    print("It's hot outside!")
elif temperature > 20:
    print("It's warm outside")
elif temperature > 10:
    print("It's cool outside")
else:
    print("It's cold outside!")
Output:
It's warm outside

The else statement must come last and acts as the default when no other condition is true.

Common Use Cases

Use Case 1: Login System

stored_password = "python123"
entered_password = "python123"

if entered_password == stored_password:
    print("Login successful")
else:
    print("Invalid password")
Output:
Login successful

Use Case 2: Discount Calculator

purchase_amount = 120

if purchase_amount >= 100:
    discount = purchase_amount * 0.10
    print(f"You get a 10% discount: ${discount}")
else:
    print("No discount available")
Output:
You get a 10% discount: $12.0

Use Case 3: Pass/Fail System

exam_score = 45
passing_score = 50

if exam_score >= passing_score:
    print("Congratulations! You passed")
else:
    print(f"Sorry, you need {passing_score - exam_score} more points to pass")
Output:
Sorry, you need 5 more points to pass

Use Case 4: File Extension Checker

filename = "document.pdf"

if filename.endswith(".pdf"):
    print("This is a PDF file")
else:
    print("This is not a PDF file")
Output:
This is a PDF file

Use Case 5: Leap Year Checker

year = 2024

if year % 4 == 0:
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")
Output:
2024 is a leap year

Common Mistakes to Avoid

Mistake 1: Missing Colon

# Wrong
if number > 0
    print("Positive")
else
    print("Not positive")

# Correct
if number > 0:
    print("Positive")
else:
    print("Not positive")

Mistake 2: Inconsistent Indentation

# Wrong
if age >= 18:
    print("Adult")
else:
  print("Minor")  # Different indentation

# Correct
if age >= 18:
    print("Adult")
else:
    print("Minor")

Mistake 3: Using elif After else

# Wrong
if x > 0:
    print("Positive")
else:
    print("Not positive")
elif x < 0:  # SyntaxError
    print("Negative")

# Correct
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")

Mistake 4: Empty Code Blocks

# Wrong
if condition:
    # Code here
else:
    # This will cause an error

# Correct - use pass for placeholder
if condition:
    print("Condition met")
else:
    pass  # Do nothing

Use <code>pass</code> for placeholder

Best Practices

Practice 1: Keep Conditions Simple and Readable

# Less readable
if not (age < 18 or not has_permission):
    print("Allowed")

# More readable
if age >= 18 and has_permission:
    print("Allowed")

Practice 2: Use Meaningful Variable Names

# Poor
if x > 100:
    y = True

# Better
if purchase_amount > 100:
    eligible_for_discount = True

Practice 3: Handle Both Paths Explicitly

# When both outcomes matter, use if else
file_exists = True

if file_exists:
    print("Loading file...")
else:
    print("Creating new file...")

When both outcomes matter, use if else

Practice 4: Avoid Deep Nesting

# Harder to read
if condition1:
    if condition2:
        if condition3:
            action()

# Better - use elif or logical operators
if condition1 and condition2 and condition3:
    action()

Try it Yourself

Experiment with if else statements

Ready
main.py
Output Console 0 ms
// Click "Run Code" to see results

Related Topics

Frequently Asked Questions

What is the difference between if and if else in Python?

An if statement only executes code when the condition is true and does nothing otherwise. An if else statement guarantees that one of two code blocks will execute—either the if block when the condition is true or the else block when it's false.

Can I have an if else without elif?

Yes, if else works perfectly without elif. The elif keyword is only needed when you want to test multiple conditions sequentially.

Do I need parentheses around conditions in Python if else statements?

No, parentheses are optional. Both if (x > 5): and if x > 5: are valid, though the latter is more commonly used in Python.

Can I use if else in one line?

Yes, Python supports the ternary operator: result = "yes" if condition else "no". This is useful for simple assignments.

What happens if I forget to indent code in an else block?

Python will raise an IndentationError because it requires consistent indentation to define code blocks.

Can else appear by itself without if?

No, else must always be paired with a preceding if statement. You cannot use else independently.