Python If-Else Statements: Complete Guide & Examples

Master Python conditional statements with this comprehensive guide covering if-else syntax, operators, nested conditions, and best practices.

Python If-Else Statements: Complete Guide

Table of Contents

1. [Introduction](#introduction) 2. [Basic Syntax](#basic-syntax) 3. [Types of Conditional Statements](#types-of-conditional-statements) 4. [Comparison Operators](#comparison-operators) 5. [Logical Operators](#logical-operators) 6. [Nested If-Else Statements](#nested-if-else-statements) 7. [Practical Examples](#practical-examples) 8. [Best Practices](#best-practices) 9. [Common Mistakes](#common-mistakes) 10. [Advanced Concepts](#advanced-concepts)

Introduction

If-else statements are fundamental control flow structures in Python that allow programs to make decisions based on certain conditions. These conditional statements enable your program to execute different blocks of code depending on whether specific conditions are true or false. They form the backbone of decision-making in programming and are essential for creating dynamic, responsive applications.

The concept of conditional execution is based on Boolean logic, where conditions evaluate to either True or False. When a condition is True, the associated code block executes; when False, the program either skips that block or executes an alternative block of code.

Basic Syntax

Simple If Statement

The most basic form of conditional statement in Python is the if statement. Here's the fundamental syntax:

`python if condition: # Code block to execute if condition is True statement1 statement2 `

Key Points: - The if keyword starts the conditional statement - The condition must evaluate to a Boolean value (True or False) - A colon (:) follows the condition - The code block is indented (typically 4 spaces) - All indented lines after the if statement belong to the conditional block

Example: `python age = 18 if age >= 18: print("You are eligible to vote") print("Welcome to the voting system") `

If-Else Statement

The if-else statement provides an alternative path when the condition is False:

`python if condition: # Code block for True condition statement1 else: # Code block for False condition statement2 `

Example: `python temperature = 25 if temperature > 30: print("It's hot outside") else: print("The weather is pleasant") `

If-Elif-Else Statement

For multiple conditions, Python provides the elif (else if) clause:

`python if condition1: # Code block for condition1 statement1 elif condition2: # Code block for condition2 statement2 elif condition3: # Code block for condition3 statement3 else: # Code block when all conditions are False statement4 `

Example: `python 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") `

Types of Conditional Statements

| Statement Type | Syntax | Use Case | Example | |----------------|---------|----------|---------| | Simple If | if condition: | Single condition check | Check if user is logged in | | If-Else | if condition: ... else: | Binary decision | Check if number is even or odd | | If-Elif-Else | if condition1: ... elif condition2: ... else: | Multiple conditions | Grade calculation system | | Nested If | if condition1: if condition2: | Complex decision trees | User authentication levels |

Detailed Examples for Each Type

#### 1. Simple If Statement `python

Check if a number is positive

number = 10 if number > 0: print(f"{number} is a positive number") result = number * 2 print(f"Double of {number} is {result}")

Check if a list is not empty

shopping_list = ["apples", "bread", "milk"] if shopping_list: print("You have items in your shopping list:") for item in shopping_list: print(f"- {item}") `

#### 2. If-Else Statement `python

Check if a number is even or odd

number = 7 if number % 2 == 0: print(f"{number} is even") else: print(f"{number} is odd")

User access control

user_role = "guest" if user_role == "admin": print("Full access granted") print("You can modify system settings") else: print("Limited access") print("You can only view content") `

#### 3. If-Elif-Else Statement `python

Weather recommendation system

weather = "rainy" if weather == "sunny": print("Perfect day for outdoor activities!") print("Don't forget sunscreen") elif weather == "rainy": print("Stay indoors or carry an umbrella") print("Good day for reading") elif weather == "snowy": print("Drive carefully") print("Dress warmly") else: print("Check the weather forecast") `

Comparison Operators

Comparison operators are used to compare values and return Boolean results. Understanding these operators is crucial for writing effective conditional statements.

| Operator | Description | Example | Result | |----------|-------------|---------|---------| | == | Equal to | 5 == 5 | True | | != | Not equal to | 5 != 3 | True | | < | Less than | 3 < 5 | True | | > | Greater than | 7 > 4 | True | | <= | Less than or equal to | 5 <= 5 | True | | >= | Greater than or equal to | 6 >= 4 | True | | is | Identity comparison | a is b | True if same object | | is not | Negative identity | a is not b | True if different objects | | in | Membership test | 'a' in 'apple' | True | | not in | Negative membership | 'z' not in 'apple' | True |

Detailed Examples of Comparison Operators

`python

Numeric comparisons

a = 10 b = 20 c = 10

print(f"a == b: {a == b}") # False print(f"a == c: {a == c}") # True print(f"a != b: {a != b}") # True print(f"a < b: {a < b}") # True print(f"a > b: {a > b}") # False print(f"a <= c: {a <= c}") # True print(f"b >= a: {b >= a}") # True

String comparisons

name1 = "Alice" name2 = "Bob" name3 = "Alice"

if name1 == name3: print("Names are identical")

if name1 != name2: print("Different names")

List comparisons

list1 = [1, 2, 3] list2 = [1, 2, 3] list3 = list1

print(f"list1 == list2: {list1 == list2}") # True (same content) print(f"list1 is list2: {list1 is list2}") # False (different objects) print(f"list1 is list3: {list1 is list3}") # True (same object)

Membership testing

fruits = ["apple", "banana", "orange"] if "apple" in fruits: print("Apple is available")

if "grape" not in fruits: print("Grape is not available") `

Logical Operators

Logical operators allow you to combine multiple conditions in a single if statement, making your code more efficient and readable.

| Operator | Description | Example | Result | |----------|-------------|---------|---------| | and | Returns True if both conditions are True | True and False | False | | or | Returns True if at least one condition is True | True or False | True | | not | Returns the opposite Boolean value | not True | False |

Truth Tables

#### AND Operator Truth Table | Condition A | Condition B | A and B | |-------------|-------------|---------| | True | True | True | | True | False | False | | False | True | False | | False | False | False |

#### OR Operator Truth Table | Condition A | Condition B | A or B | |-------------|-------------|--------| | True | True | True | | True | False | True | | False | True | True | | False | False | False |

#### NOT Operator Truth Table | Condition | not Condition | |-----------|---------------| | True | False | | False | True |

Practical Examples with Logical Operators

`python

AND operator examples

age = 25 has_license = True

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

Multiple AND conditions

username = "admin" password = "secret123" is_active = True

if username == "admin" and password == "secret123" and is_active: print("Login successful") print("Welcome to the admin panel") else: print("Login failed")

OR operator examples

day = "Saturday" is_holiday = False

if day == "Saturday" or day == "Sunday" or is_holiday: print("No work today!") else: print("It's a working day")

NOT operator examples

is_raining = False if not is_raining: print("Good weather for a walk") else: print("Better stay indoors")

Complex logical expressions

temperature = 22 humidity = 60 is_sunny = True

if (temperature >= 20 and temperature <= 30) and humidity < 70 and is_sunny: print("Perfect weather conditions!") elif temperature > 30 or humidity > 80: print("It might be uncomfortable outside") else: print("Weather is acceptable") `

Nested If-Else Statements

Nested if-else statements allow you to create more complex decision-making structures by placing one conditional statement inside another. This is useful when you need to check multiple related conditions in a hierarchical manner.

Basic Nested Structure

`python if outer_condition: if inner_condition1: # Code for both outer and inner_condition1 being True pass elif inner_condition2: # Code for outer True and inner_condition2 True pass else: # Code for outer True but all inner conditions False pass else: # Code for outer_condition being False pass `

Practical Examples of Nested If-Else

`python

Student grade and attendance system

grade = 85 attendance = 75 behavior = "good"

if grade >= 60: # Student passed print("Student has passed the course") if attendance >= 80: print("Excellent attendance") if behavior == "excellent": print("Eligible for honor roll") elif behavior == "good": print("Eligible for merit certificate") else: print("Needs improvement in behavior") elif attendance >= 70: print("Good attendance") if grade >= 85: print("High achiever despite moderate attendance") else: print("Poor attendance - needs improvement") if grade >= 90: print("Exceptional academic performance") else: print("Both attendance and grade need attention")

else: # Student failed print("Student has failed the course") if attendance >= 80: print("Good attendance but academic support needed") else: print("Both attendance and academic performance need improvement") `

Complex Nested Example: Banking System

`python

Banking system with multiple checks

account_balance = 1500 withdrawal_amount = 200 account_type = "premium" has_overdraft = True daily_limit = 1000 daily_withdrawn = 300

if withdrawal_amount > 0: # Valid withdrawal amount print("Processing withdrawal request...") if account_balance >= withdrawal_amount: # Sufficient balance print("Sufficient balance available") if (daily_withdrawn + withdrawal_amount) <= daily_limit: # Within daily limit print("Within daily withdrawal limit") if account_type == "premium": print("Premium account - no fees") print(f"Withdrawal of ${withdrawal_amount} approved") elif account_type == "standard": if withdrawal_amount > 500: print("Large withdrawal fee applies") else: print("Standard withdrawal - minimal fee") print(f"Withdrawal of ${withdrawal_amount} approved") else: # Basic account print("Basic account - standard fees apply") print(f"Withdrawal of ${withdrawal_amount} approved") else: # Exceeds daily limit print("Exceeds daily withdrawal limit") remaining_limit = daily_limit - daily_withdrawn print(f"You can withdraw up to ${remaining_limit} today") else: # Insufficient balance print("Insufficient balance") if has_overdraft: overdraft_limit = 500 total_available = account_balance + overdraft_limit if total_available >= withdrawal_amount: print("Overdraft protection available") overdraft_used = withdrawal_amount - account_balance print(f"Using ${overdraft_used} from overdraft") print(f"Withdrawal of ${withdrawal_amount} approved") else: print("Even with overdraft, insufficient funds") print(f"Maximum available: ${total_available}") else: print("No overdraft protection") print(f"Current balance: ${account_balance}")

else: # Invalid withdrawal amount print("Invalid withdrawal amount") `

Practical Examples

Example 1: User Authentication System

`python def authenticate_user(): # User credentials stored_username = "admin" stored_password = "secure123" max_attempts = 3 attempts = 0 while attempts < max_attempts: username = input("Enter username: ") password = input("Enter password: ") if username == stored_username and password == stored_password: print("Authentication successful!") print("Welcome to the system") # Check user privileges if username == "admin": print("Admin privileges granted") print("You have full system access") else: print("User privileges granted") print("Limited system access") return True else: attempts += 1 remaining = max_attempts - attempts if remaining > 0: print(f"Invalid credentials. {remaining} attempts remaining") if username != stored_username: print("Hint: Check your username") elif password != stored_password: print("Hint: Check your password") else: print("Maximum attempts reached. Account locked.") return False

Call the function

authenticate_user()

`

Example 2: E-commerce Discount Calculator

`python def calculate_discount(purchase_amount, customer_type, is_member, coupon_code): """ Calculate discount based on multiple criteria """ base_discount = 0 additional_discount = 0 final_amount = purchase_amount print(f"Original amount: ${purchase_amount}") # Customer type discount if customer_type == "premium": base_discount = 0.15 # 15% discount print("Premium customer: 15% base discount") elif customer_type == "gold": base_discount = 0.10 # 10% discount print("Gold customer: 10% base discount") elif customer_type == "silver": base_discount = 0.05 # 5% discount print("Silver customer: 5% base discount") else: base_discount = 0 print("Regular customer: No base discount") # Membership additional discount if is_member: additional_discount += 0.05 # Additional 5% for members print("Membership bonus: Additional 5% discount") # Purchase amount tiers if purchase_amount >= 1000: additional_discount += 0.10 # 10% for large purchases print("Large purchase bonus: Additional 10% discount") elif purchase_amount >= 500: additional_discount += 0.05 # 5% for medium purchases print("Medium purchase bonus: Additional 5% discount") # Coupon code validation valid_coupons = { "SAVE20": 0.20, "WELCOME10": 0.10, "FIRST5": 0.05 } if coupon_code in valid_coupons: coupon_discount = valid_coupons[coupon_code] print(f"Coupon '{coupon_code}': {coupon_discount*100}% discount") # Apply the best discount (coupon vs accumulated discounts) total_other_discount = base_discount + additional_discount if coupon_discount > total_other_discount: final_discount = coupon_discount print("Coupon provides better discount - applied") else: final_discount = total_other_discount print("Accumulated discounts are better - applied") else: final_discount = base_discount + additional_discount if coupon_code: print(f"Invalid coupon code: '{coupon_code}'") # Calculate final amount discount_amount = purchase_amount * final_discount final_amount = purchase_amount - discount_amount # Display results print(f"\nDiscount Summary:") print(f"Total discount: {final_discount*100:.1f}%") print(f"Discount amount: ${discount_amount:.2f}") print(f"Final amount: ${final_amount:.2f}") print(f"You saved: ${discount_amount:.2f}") return final_amount

Test the function

result = calculate_discount(750, "gold", True, "SAVE20") `

Example 3: Weather-Based Activity Recommender

`python def recommend_activity(temperature, humidity, wind_speed, precipitation, season): """ Recommend activities based on weather conditions """ print("Weather-Based Activity Recommender") print("=" * 40) print(f"Temperature: {temperature}°C") print(f"Humidity: {humidity}%") print(f"Wind Speed: {wind_speed} km/h") print(f"Precipitation: {precipitation}mm") print(f"Season: {season}") print("-" * 40) recommendations = [] # Temperature-based recommendations if temperature >= 25: if humidity < 60: recommendations.append("Perfect for outdoor sports") recommendations.append("Great for swimming") if wind_speed < 15: recommendations.append("Ideal for picnics") else: recommendations.append("Good for kite flying") else: recommendations.append("Stay hydrated - high humidity") recommendations.append("Indoor activities recommended") elif temperature >= 15: recommendations.append("Comfortable for walking") recommendations.append("Good for outdoor photography") if season == "spring": recommendations.append("Perfect for gardening") elif season == "autumn": recommendations.append("Great for hiking") elif temperature >= 5: recommendations.append("Dress warmly for outdoor activities") if season == "winter": if precipitation > 0: recommendations.append("Possible snow activities") else: recommendations.append("Clear winter day - good for skiing") else: recommendations.append("Very cold - indoor activities recommended") recommendations.append("Hot drinks and warm clothing advised") # Precipitation-based adjustments if precipitation > 10: recommendations = ["Heavy rain - stay indoors"] recommendations.append("Good day for reading or movies") recommendations.append("Indoor gym or yoga") elif precipitation > 0: recommendations.append("Light rain - carry umbrella") recommendations.append("Good for indoor shopping") # Wind-based adjustments if wind_speed > 25: recommendations.append("Very windy - avoid outdoor activities") elif wind_speed > 15: recommendations.append("Windy conditions - secure loose items") # Special seasonal recommendations if season == "summer": if temperature > 30 and humidity > 70: recommendations.append("Heat warning - limit outdoor exposure") recommendations.append("Use air conditioning") elif season == "winter": if temperature < 0: recommendations.append("Freezing conditions - dress in layers") # Display recommendations print("Recommendations:") if recommendations: for i, recommendation in enumerate(recommendations, 1): print(f"{i}. {recommendation}") else: print("No specific recommendations - moderate conditions") return recommendations

Test the function

weather_recommendations = recommend_activity(22, 45, 8, 0, "spring") `

Best Practices

1. Code Readability and Structure

| Practice | Good Example | Poor Example | |----------|--------------|--------------| | Use clear variable names | is_authenticated = True | flag = True | | Avoid deep nesting | Use functions to break complexity | Multiple nested levels | | Use parentheses for complex conditions | if (a > b) and (c < d): | if a > b and c < d: | | Consistent indentation | Always use 4 spaces | Mixed tabs and spaces |

2. Optimization Techniques

`python

Good: Early return pattern

def process_user(user_data): if not user_data: return "No user data provided" if not user_data.get('email'): return "Email is required" if not user_data.get('age') or user_data['age'] < 18: return "Must be 18 or older" # Process valid user return "User processed successfully"

Poor: Deep nesting

def process_user_poor(user_data): if user_data: if user_data.get('email'): if user_data.get('age') and user_data['age'] >= 18: # Process valid user return "User processed successfully" else: return "Must be 18 or older" else: return "Email is required" else: return "No user data provided" `

3. Using Truthiness in Python

`python

Python objects have inherent truthiness

Empty containers are False, non-empty are True

Good: Leveraging truthiness

user_list = [] if user_list: # More Pythonic print("Users found") else: print("No users")

Less Pythonic

if len(user_list) > 0: print("Users found") else: print("No users")

Truthiness examples

values_and_truthiness = [ ([], False), # Empty list ([1, 2], True), # Non-empty list ("", False), # Empty string ("hello", True), # Non-empty string (0, False), # Zero (42, True), # Non-zero number (None, False), # None value ({}, False), # Empty dictionary ({"key": "value"}, True) # Non-empty dictionary ]

for value, expected in values_and_truthiness: actual = bool(value) print(f"bool({value}) = {actual} (Expected: {expected})") `

Common Mistakes

1. Assignment vs Comparison

`python

WRONG: Using assignment (=) instead of comparison (==)

x = 10 if x = 5: # This will cause a SyntaxError print("x is 5")

CORRECT: Using comparison operator

if x == 5: print("x is 5") else: print("x is not 5") `

2. Incorrect Indentation

`python

WRONG: Inconsistent indentation

age = 20 if age >= 18: print("Adult") # IndentationError: expected an indented block print("Can vote") # Mixed indentation

CORRECT: Consistent indentation

if age >= 18: print("Adult") print("Can vote") `

3. Logical Operator Confusion

`python

WRONG: Incorrect logical operator usage

age = 25 if age >= 18 and <= 65: # SyntaxError print("Working age")

CORRECT: Proper logical operator usage

if age >= 18 and age <= 65: print("Working age")

BETTER: Using chained comparisons

if 18 <= age <= 65: print("Working age") `

4. Float Comparison Issues

`python

PROBLEMATIC: Direct float comparison

result = 0.1 + 0.2 if result == 0.3: # This might be False due to floating-point precision print("Equal") else: print("Not equal") # This will likely print

CORRECT: Using tolerance for float comparison

tolerance = 1e-9 if abs(result - 0.3) < tolerance: print("Equal (within tolerance)") else: print("Not equal") `

Advanced Concepts

1. Ternary Operator (Conditional Expression)

The ternary operator provides a concise way to write simple if-else statements in a single line.

`python

Basic syntax: value_if_true if condition else value_if_false

Traditional if-else

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

Ternary operator equivalent

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

More examples

numbers = [1, 2, 3, 4, 5] result = "even" if len(numbers) % 2 == 0 else "odd"

Nested ternary operators (use sparingly)

score = 85 grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"

Better approach for multiple conditions

def get_grade(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" else: return "F"

grade = get_grade(score) `

2. Short-Circuit Evaluation

Python uses short-circuit evaluation for logical operators, which can be leveraged for efficient and safe code.

`python

AND short-circuiting

def expensive_operation(): print("Expensive operation called") return True

flag = False

expensive_operation() won't be called because flag is False

if flag and expensive_operation(): print("Both conditions met")

OR short-circuiting

flag = True

expensive_operation() won't be called because flag is True

if flag or expensive_operation(): print("At least one condition met")

Practical example: Safe attribute access

user_data = None

This won't raise an AttributeError

if user_data and user_data.get('name'): print(f"User name: {user_data['name']}")

Safe list access

items = [] if items and items[0] > 10: # Won't cause IndexError print("First item is greater than 10") `

3. Using 'in' for Multiple Comparisons

`python

Instead of multiple OR conditions

user_role = "editor"

Less efficient

if user_role == "admin" or user_role == "editor" or user_role == "moderator": print("User has editing privileges")

More efficient and readable

if user_role in ["admin", "editor", "moderator"]: print("User has editing privileges")

With sets for even better performance (for large collections)

privileged_roles = {"admin", "editor", "moderator", "supervisor"} if user_role in privileged_roles: print("User has editing privileges")

Checking multiple conditions with any() and all()

permissions = ["read", "write", "delete"] required_permissions = ["read", "write"]

Check if user has all required permissions

if all(perm in permissions for perm in required_permissions): print("User has all required permissions")

Check if user has any of the permissions

admin_permissions = ["admin", "super_user"] if any(perm in permissions for perm in admin_permissions): print("User has admin-level permissions") `

4. Exception Handling with Conditionals

`python

Combining conditionals with try-except for robust code

def safe_divide(a, b): if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): return "Error: Both arguments must be numbers" if b == 0: return "Error: Division by zero" try: result = a / b if result > 1000: return f"Warning: Large result {result:.2f}" elif result < 0.001 and result > 0: return f"Warning: Very small result {result:.6f}" else: return result except Exception as e: return f"Unexpected error: {e}"

Test the function

print(safe_divide(10, 2)) # 5.0 print(safe_divide(10, 0)) # Error: Division by zero print(safe_divide(10, "2")) # Error: Both arguments must be numbers `

5. Match-Case Statement (Python 3.10+)

Python 3.10 introduced the match-case statement, which is similar to switch statements in other languages.

`python

Traditional if-elif-else

def handle_http_status_old(status_code): if status_code == 200: return "OK" elif status_code == 404: return "Not Found" elif status_code == 500: return "Internal Server Error" elif status_code in [301, 302]: return "Redirect" else: return "Unknown Status"

Using match-case (Python 3.10+)

def handle_http_status_new(status_code): match status_code: case 200: return "OK" case 404: return "Not Found" case 500: return "Internal Server Error" case 301 | 302: # Multiple values return "Redirect" case code if 400 <= code < 500: # Guard condition return "Client Error" case code if 500 <= code < 600: # Guard condition return "Server Error" case _: # Default case return "Unknown Status"

Advanced match-case with data structures

def process_data(data): match data: case {"type": "user", "name": str(name)} if name: return f"Processing user: {name}" case {"type": "product", "id": int(product_id)} if product_id > 0: return f"Processing product ID: {product_id}" case {"type": "order", "items": list(items)} if items: return f"Processing order with {len(items)} items" case _: return "Unknown data format"

Test match-case examples

print(handle_http_status_new(200)) # OK print(handle_http_status_new(404)) # Not Found print(handle_http_status_new(403)) # Client Error

test_data = {"type": "user", "name": "Alice"} print(process_data(test_data)) # Processing user: Alice `

This comprehensive guide covers the fundamental and advanced aspects of if-else statements in Python. Understanding these concepts will enable you to write more efficient, readable, and maintainable code. Practice with the provided examples and gradually incorporate the advanced techniques into your programming workflow.

Tags

  • boolean logic
  • conditional statements
  • control flow
  • decision-making
  • python syntax

Related Articles

Related Books - Expand Your Knowledge

Explore these Python books to deepen your understanding:

Browse all IT books

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Python If-Else Statements: Complete Guide &amp; Examples