Python if-else Conditions: Complete Guide & Best Practices

Master Python conditional statements with comprehensive examples, comparison operators, nested conditions, and best practices for clean code.

Using if-else Conditions in Python

Table of Contents

1. [Introduction to Conditional Statements](#introduction) 2. [Basic if Statement](#basic-if) 3. [if-else Statement](#if-else) 4. [if-elif-else Statement](#if-elif-else) 5. [Nested Conditions](#nested-conditions) 6. [Comparison Operators](#comparison-operators) 7. [Logical Operators](#logical-operators) 8. [Membership and Identity Operators](#membership-identity) 9. [Conditional Expressions (Ternary Operator)](#ternary) 10. [Best Practices](#best-practices) 11. [Common Patterns and Examples](#patterns) 12. [Error Handling with Conditions](#error-handling)

Introduction to Conditional Statements {#introduction}

Conditional statements in Python allow programs to make decisions based on different conditions. They control the flow of execution by evaluating expressions that return Boolean values (True or False). The primary conditional statements in Python are if, elif, and else.

Key Characteristics

| Feature | Description | |---------|-------------| | Syntax | Uses keywords if, elif, else followed by colons | | Indentation | Code blocks are defined by consistent indentation | | Boolean Context | Conditions are evaluated in Boolean context | | Multiple Conditions | Support for complex logical expressions | | Nested Structure | Conditions can be nested within other conditions |

Truth Values in Python

Python evaluates various data types in Boolean context:

| Data Type | True Values | False Values | |-----------|-------------|--------------| | Numbers | Non-zero numbers | 0, 0.0, 0j | | Strings | Non-empty strings | Empty string "" | | Collections | Non-empty lists, tuples, sets, dicts | Empty collections | | None | Never | None | | Boolean | True | False |

Basic if Statement {#basic-if}

The if statement is the simplest form of conditional execution. It executes a block of code only when a specified condition is True.

Syntax Structure

`python if condition: # Code block to execute when condition is True statement1 statement2 # More statements... `

Basic Examples

`python

Simple numeric condition

age = 18 if age >= 18: print("You are eligible to vote")

String condition

username = "admin" if username == "admin": print("Access granted to admin panel")

Boolean variable

is_logged_in = True if is_logged_in: print("Welcome back!")

List condition (checking if not empty)

shopping_cart = ["apple", "banana", "orange"] if shopping_cart: print(f"You have {len(shopping_cart)} items in your cart") `

Notes on Basic if Statements

- The condition after if must evaluate to a Boolean value - Indentation is crucial in Python - typically 4 spaces - Multiple statements can be executed within the if block - If the condition is False, the entire block is skipped

if-else Statement {#if-else}

The if-else statement provides an alternative path of execution when the condition is False.

Syntax Structure

`python if condition: # Code executed when condition is True true_statements else: # Code executed when condition is False false_statements `

Comprehensive Examples

`python

Age verification system

def check_age_eligibility(age): if age >= 21: print(f"Age {age}: Eligible for all activities") return "full_access" else: print(f"Age {age}: Limited access") return "restricted_access"

Temperature control system

temperature = 75 if temperature > 80: print("Turn on air conditioning") ac_status = "ON" fan_speed = "HIGH" else: print("Temperature is comfortable") ac_status = "OFF" fan_speed = "LOW"

File processing example

filename = "data.txt" if filename.endswith('.txt'): print("Processing text file") file_type = "text" processor = "text_handler" else: print("Unknown file type") file_type = "unknown" processor = "default_handler" `

Practical Applications

| Use Case | Example Scenario | |----------|------------------| | User Authentication | Check credentials and grant/deny access | | Input Validation | Verify user input meets requirements | | Error Handling | Handle success/failure scenarios | | Configuration | Set different parameters based on conditions |

if-elif-else Statement {#if-elif-else}

The elif (else if) statement allows checking multiple conditions in sequence. It's more efficient than multiple separate if statements.

Syntax Structure

`python if condition1: # Code for condition1 statements1 elif condition2: # Code for condition2 statements2 elif condition3: # Code for condition3 statements3 else: # Default code when no conditions are met default_statements `

Detailed Examples

`python

Grade calculation system

def calculate_grade(score): if score >= 90: grade = 'A' message = "Excellent performance!" gpa_points = 4.0 elif score >= 80: grade = 'B' message = "Good work!" gpa_points = 3.0 elif score >= 70: grade = 'C' message = "Satisfactory" gpa_points = 2.0 elif score >= 60: grade = 'D' message = "Needs improvement" gpa_points = 1.0 else: grade = 'F' message = "Failed - please retake" gpa_points = 0.0 return { 'grade': grade, 'message': message, 'gpa_points': gpa_points, 'score': score }

Traffic light system

def traffic_light_action(color): if color.lower() == 'green': action = "GO" duration = 30 next_color = "yellow" elif color.lower() == 'yellow': action = "CAUTION" duration = 5 next_color = "red" elif color.lower() == 'red': action = "STOP" duration = 25 next_color = "green" else: action = "ERROR" duration = 0 next_color = "unknown" return { 'current_color': color, 'action': action, 'duration': duration, 'next_color': next_color }

Season determination

def determine_season(month): if month in [12, 1, 2]: season = "Winter" temperature_range = "Cold (20-40°F)" activities = ["skiing", "ice skating", "hot chocolate"] elif month in [3, 4, 5]: season = "Spring" temperature_range = "Mild (50-70°F)" activities = ["gardening", "hiking", "picnics"] elif month in [6, 7, 8]: season = "Summer" temperature_range = "Hot (70-90°F)" activities = ["swimming", "camping", "barbecues"] elif month in [9, 10, 11]: season = "Fall" temperature_range = "Cool (40-70°F)" activities = ["leaf watching", "apple picking", "bonfires"] else: season = "Invalid" temperature_range = "Unknown" activities = [] return { 'month': month, 'season': season, 'temperature_range': temperature_range, 'activities': activities } `

Nested Conditions {#nested-conditions}

Nested conditions involve placing if-else statements within other if-else statements, allowing for more complex decision-making logic.

Structure and Examples

`python

Complex user access control system

def check_user_access(user_role, user_department, security_clearance, time_of_day): if user_role == "admin": if security_clearance >= 5: if time_of_day >= 6 and time_of_day <= 22: access_level = "full_admin" permissions = ["read", "write", "delete", "modify_users", "system_config"] else: access_level = "limited_admin" permissions = ["read", "write", "emergency_access"] else: access_level = "basic_admin" permissions = ["read", "write", "basic_config"] elif user_role == "manager": if user_department == "IT": if security_clearance >= 3: access_level = "it_manager" permissions = ["read", "write", "user_management", "department_config"] else: access_level = "basic_manager" permissions = ["read", "write", "team_management"] else: access_level = "department_manager" permissions = ["read", "write", "department_reports"] else: if security_clearance >= 2: access_level = "senior_user" permissions = ["read", "write", "personal_data"] else: access_level = "basic_user" permissions = ["read", "personal_data"] return { 'access_level': access_level, 'permissions': permissions, 'user_info': { 'role': user_role, 'department': user_department, 'clearance': security_clearance, 'time': time_of_day } }

Banking transaction validation

def validate_transaction(account_balance, transaction_amount, transaction_type, daily_limit_used): if transaction_type == "withdrawal": if account_balance >= transaction_amount: if daily_limit_used + transaction_amount <= 1000: if transaction_amount <= 500: status = "approved" fee = 0 message = "Transaction approved" else: status = "approved_with_fee" fee = 2.50 message = "Large withdrawal fee applied" else: status = "denied" fee = 0 message = "Daily limit exceeded" else: status = "denied" fee = 0 message = "Insufficient funds" elif transaction_type == "deposit": if transaction_amount <= 10000: status = "approved" fee = 0 message = "Deposit accepted" else: status = "pending_review" fee = 0 message = "Large deposit requires verification" else: status = "error" fee = 0 message = "Invalid transaction type" return { 'status': status, 'fee': fee, 'message': message, 'final_balance': account_balance + (transaction_amount if transaction_type == "deposit" and status == "approved" else 0) - (transaction_amount + fee if transaction_type == "withdrawal" and "approved" in status else 0) } `

Comparison Operators {#comparison-operators}

Comparison operators are used to compare values and return Boolean results.

Operator Reference Table

| Operator | Description | Example | Result | |----------|-------------|---------|---------| | == | Equal to | 5 == 5 | True | | != | Not equal to | 5 != 3 | True | | < | Less than | 3 < 5 | True | | <= | Less than or equal | 5 <= 5 | True | | > | Greater than | 7 > 3 | True | | >= | Greater than or equal | 5 >= 3 | True |

Practical Examples

`python

Numeric comparisons

def analyze_test_scores(scores): results = {} for i, score in enumerate(scores): student_id = f"student_{i+1}" if score == 100: results[student_id] = {"performance": "perfect", "bonus": True} elif score >= 95: results[student_id] = {"performance": "excellent", "bonus": True} elif score >= 85: results[student_id] = {"performance": "very_good", "bonus": False} elif score >= 75: results[student_id] = {"performance": "good", "bonus": False} elif score >= 65: results[student_id] = {"performance": "satisfactory", "bonus": False} else: results[student_id] = {"performance": "needs_improvement", "bonus": False} return results

String comparisons

def process_user_commands(command): command = command.lower().strip() if command == "help": return "Available commands: start, stop, pause, resume, help, quit" elif command == "start": return "System starting..." elif command == "stop": return "System stopping..." elif command != "quit": return f"Unknown command: {command}. Type 'help' for available commands." else: return "Goodbye!"

Date and time comparisons

from datetime import datetime, date

def check_event_eligibility(birth_date, event_date, min_age=18): age = (event_date - birth_date).days // 365 if age >= min_age: if event_date > date.today(): return { "eligible": True, "message": f"Eligible for event (Age: {age})", "days_until_event": (event_date - date.today()).days } elif event_date == date.today(): return { "eligible": True, "message": f"Event is today! (Age: {age})", "days_until_event": 0 } else: return { "eligible": False, "message": "Event has already passed", "days_until_event": -1 } else: return { "eligible": False, "message": f"Too young (Age: {age}, Required: {min_age})", "days_until_event": None } `

Logical Operators {#logical-operators}

Logical operators combine multiple conditions and return Boolean values.

Logical Operators Table

| Operator | Description | Truth Table | Example | |----------|-------------|-------------|---------| | and | Returns True if both conditions are True | True and True = True
True and False = False
False and True = False
False and False = False | age >= 18 and has_license | | or | Returns True if at least one condition is True | True or True = True
True or False = True
False or True = True
False or False = False | is_weekend or is_holiday | | not | Returns the opposite Boolean value | not True = False
not False = True | not is_banned |

Complex Examples

`python

Advanced user authentication system

def authenticate_user(username, password, is_account_active, failed_attempts, last_login_hours_ago, two_factor_enabled, two_factor_code=None): # Check basic credentials if username == "admin" and password == "secure123": credentials_valid = True elif username == "user" and password == "pass456": credentials_valid = True else: credentials_valid = False # Complex authentication logic if credentials_valid and is_account_active and failed_attempts < 3: if two_factor_enabled: if two_factor_code and two_factor_code == "123456": if last_login_hours_ago <= 24 or username == "admin": return { "status": "success", "message": "Authentication successful with 2FA", "access_level": "full" } else: return { "status": "warning", "message": "Long time since last login - limited access", "access_level": "limited" } else: return { "status": "failed", "message": "Invalid 2FA code", "access_level": "none" } else: if last_login_hours_ago <= 168: # 1 week return { "status": "success", "message": "Authentication successful", "access_level": "standard" } else: return { "status": "warning", "message": "Please enable 2FA for security", "access_level": "limited" } elif not credentials_valid: return { "status": "failed", "message": "Invalid username or password", "access_level": "none" } elif not is_account_active: return { "status": "failed", "message": "Account is deactivated", "access_level": "none" } else: return { "status": "locked", "message": "Account locked due to too many failed attempts", "access_level": "none" }

Weather-based activity recommendation

def recommend_activity(temperature, humidity, wind_speed, precipitation, is_weekend): if temperature >= 70 and temperature <= 85: if humidity < 60 and precipitation == 0: if wind_speed < 15: if is_weekend: return { "activity": "Outdoor sports or picnic", "reason": "Perfect weather conditions on weekend", "preparation": ["sunscreen", "water", "comfortable clothes"] } else: return { "activity": "Walk or outdoor lunch", "reason": "Great weather for outdoor activities", "preparation": ["light jacket", "sunglasses"] } else: return { "activity": "Indoor activities near windows", "reason": "Good temperature but too windy", "preparation": ["warm clothes if going out"] } elif precipitation > 0: return { "activity": "Indoor entertainment", "reason": "Rain or snow expected", "preparation": ["umbrella", "waterproof clothing"] } else: return { "activity": "Light indoor activities", "reason": "High humidity makes outdoor activities uncomfortable", "preparation": ["stay hydrated", "light clothing"] } elif temperature < 32 or temperature > 95: return { "activity": "Indoor activities with climate control", "reason": "Extreme temperature conditions", "preparation": ["appropriate climate protection"] } else: return { "activity": "Moderate indoor/outdoor activities", "reason": "Acceptable but not ideal conditions", "preparation": ["weather-appropriate clothing"] } `

Membership and Identity Operators {#membership-identity}

These operators check for membership in sequences and object identity.

Operators Table

| Operator | Description | Example | Use Case | |----------|-------------|---------|----------| | in | Returns True if value is found in sequence | 'a' in 'apple' | Check if item exists | | not in | Returns True if value is not found in sequence | 'z' not in 'apple' | Verify absence | | is | Returns True if variables point to same object | x is None | Identity comparison | | is not | Returns True if variables point to different objects | x is not None | Identity comparison |

Comprehensive Examples

`python

Content filtering system

def filter_content(text, banned_words, allowed_categories, user_age, content_rating): banned_words = [word.lower() for word in banned_words] text_lower = text.lower() # Check for banned words contains_banned = any(word in text_lower for word in banned_words) # Age-based content filtering if user_age < 13: allowed_ratings = ['G'] elif user_age < 17: allowed_ratings = ['G', 'PG', 'PG-13'] else: allowed_ratings = ['G', 'PG', 'PG-13', 'R'] # Category check valid_category = content_rating in allowed_categories age_appropriate = content_rating in allowed_ratings if contains_banned: return { "approved": False, "reason": "Content contains banned words", "action": "block" } elif not valid_category: return { "approved": False, "reason": f"Category '{content_rating}' not in allowed categories", "action": "review" } elif not age_appropriate: return { "approved": False, "reason": f"Content rating '{content_rating}' not appropriate for age {user_age}", "action": "age_restrict" } else: return { "approved": True, "reason": "Content passed all filters", "action": "approve" }

System configuration validator

def validate_configuration(config): required_keys = ['database_url', 'api_key', 'debug_mode', 'port'] optional_keys = ['cache_timeout', 'log_level', 'max_connections'] valid_log_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] validation_results = { "valid": True, "errors": [], "warnings": [] } # Check for required keys for key in required_keys: if key not in config: validation_results["valid"] = False validation_results["errors"].append(f"Missing required configuration: {key}") # Validate specific configurations if 'database_url' in config: if config['database_url'] is None or config['database_url'] == "": validation_results["valid"] = False validation_results["errors"].append("Database URL cannot be empty") if 'port' in config: if not isinstance(config['port'], int) or config['port'] < 1 or config['port'] > 65535: validation_results["valid"] = False validation_results["errors"].append("Port must be an integer between 1 and 65535") if 'log_level' in config: if config['log_level'] not in valid_log_levels: validation_results["warnings"].append(f"Log level '{config['log_level']}' not in recommended levels: {valid_log_levels}") # Check for unknown keys all_known_keys = required_keys + optional_keys for key in config: if key not in all_known_keys: validation_results["warnings"].append(f"Unknown configuration key: {key}") return validation_results `

Conditional Expressions (Ternary Operator) {#ternary}

Python's conditional expression provides a concise way to write simple if-else statements in a single line.

Syntax

`python value_if_true if condition else value_if_false `

Examples and Use Cases

`python

Basic ternary operations

def process_user_data(users): processed_users = [] for user in users: # Simple ternary for status status = "active" if user.get('last_login_days', 999) <= 30 else "inactive" # Ternary for display name display_name = user['username'] if user.get('full_name') is None else user['full_name'] # Ternary for access level access_level = "admin" if user.get('is_admin', False) else "user" # Nested ternary (use sparingly) priority = "high" if user.get('subscription') == "premium" else ("medium" if user.get('subscription') == "standard" else "low") processed_users.append({ 'id': user['id'], 'display_name': display_name, 'status': status, 'access_level': access_level, 'priority': priority, 'badge': "VIP" if user.get('subscription') == "premium" and status == "active" else "Standard" }) return processed_users

Mathematical operations with ternary

def calculate_discount(price, customer_type, order_quantity): # Base discount calculation base_discount = 0.1 if customer_type == "premium" else (0.05 if customer_type == "standard" else 0) # Quantity bonus quantity_bonus = 0.05 if order_quantity >= 10 else (0.02 if order_quantity >= 5 else 0) # Total discount (capped at 25%) total_discount = min(base_discount + quantity_bonus, 0.25) # Final price calculation discounted_price = price * (1 - total_discount) return { 'original_price': price, 'discount_rate': total_discount, 'discount_amount': price * total_discount, 'final_price': discounted_price, 'savings_message': f"You saved ${price * total_discount:.2f}!" if total_discount > 0 else "No discount applied" }

String formatting with ternary

def format_time_message(hours, minutes, is_24_hour_format=True): if is_24_hour_format: return f"{hours:02d}:{minutes:02d}" else: period = "AM" if hours < 12 else "PM" display_hour = hours if hours <= 12 else hours - 12 display_hour = 12 if display_hour == 0 else display_hour return f"{display_hour}:{minutes:02d} {period}"

List comprehension with ternary

def process_scores(scores): # Convert scores to grades using ternary in list comprehension grades = [ 'A' if score >= 90 else 'B' if score >= 80 else 'C' if score >= 70 else 'D' if score >= 60 else 'F' for score in scores ] # Create pass/fail list pass_fail = ["PASS" if score >= 60 else "FAIL" for score in scores] # Combine results return list(zip(scores, grades, pass_fail)) `

Best Practices {#best-practices}

Code Organization and Readability

| Practice | Good Example | Poor Example | |----------|--------------|--------------| | Avoid Deep Nesting | Use early returns | Multiple nested if statements | | Use Descriptive Conditions | if user_is_authenticated: | if x == True: | | Consistent Indentation | 4 spaces throughout | Mixed tabs and spaces | | Logical Grouping | Related conditions together | Scattered condition checks |

Improved Code Examples

`python

Good practice: Early returns to reduce nesting

def process_order(order_data): # Validate input early if not order_data: return {"status": "error", "message": "No order data provided"} if 'customer_id' not in order_data: return {"status": "error", "message": "Customer ID required"} if 'items' not in order_data or not order_data['items']: return {"status": "error", "message": "Order must contain items"} # Process valid order total_amount = sum(item['price'] * item['quantity'] for item in order_data['items']) if total_amount <= 0: return {"status": "error", "message": "Order total must be positive"} # Apply business logic shipping_cost = 0 if total_amount >= 50 else 5.99 tax_rate = 0.08 tax_amount = total_amount * tax_rate final_total = total_amount + shipping_cost + tax_amount return { "status": "success", "order_summary": { "subtotal": total_amount, "shipping": shipping_cost, "tax": tax_amount, "total": final_total } }

Good practice: Extract complex conditions into functions

def is_business_hours(current_time): return 9 <= current_time.hour < 17 and current_time.weekday() < 5

def is_premium_customer(customer): return customer.get('subscription_type') == 'premium' and customer.get('account_status') == 'active'

def calculate_support_priority(ticket, customer, current_time): if ticket['severity'] == 'critical': return 'immediate' if is_premium_customer(customer): if is_business_hours(current_time): return 'high' else: return 'medium' if ticket['severity'] == 'high' and is_business_hours(current_time): return 'medium' return 'low'

Good practice: Use constants for magic numbers

class OrderConstants: FREE_SHIPPING_THRESHOLD = 50 STANDARD_SHIPPING_COST = 5.99 TAX_RATE = 0.08 BULK_ORDER_QUANTITY = 10 BULK_DISCOUNT_RATE = 0.1

def calculate_order_total(items, customer_type="standard"): subtotal = sum(item['price'] * item['quantity'] for item in items) # Apply bulk discount total_quantity = sum(item['quantity'] for item in items) if total_quantity >= OrderConstants.BULK_ORDER_QUANTITY: subtotal *= (1 - OrderConstants.BULK_DISCOUNT_RATE) # Calculate shipping shipping = 0 if subtotal >= OrderConstants.FREE_SHIPPING_THRESHOLD else OrderConstants.STANDARD_SHIPPING_COST # Calculate tax tax = subtotal * OrderConstants.TAX_RATE return { 'subtotal': round(subtotal, 2), 'shipping': shipping, 'tax': round(tax, 2), 'total': round(subtotal + shipping + tax, 2) } `

Common Patterns and Examples {#patterns}

Pattern Matching Alternatives

`python

Dictionary-based dispatch pattern

def handle_user_action(action, user_data): action_handlers = { 'login': lambda: authenticate_user(user_data), 'logout': lambda: logout_user(user_data), 'update_profile': lambda: update_user_profile(user_data), 'delete_account': lambda: delete_user_account(user_data), 'change_password': lambda: change_user_password(user_data) } if action in action_handlers: return action_handlers[action]() else: return {"status": "error", "message": f"Unknown action: {action}"}

State machine pattern

class OrderState: def __init__(self): self.state = "pending" self.transitions = { "pending": ["confirmed", "cancelled"], "confirmed": ["processing", "cancelled"], "processing": ["shipped", "cancelled"], "shipped": ["delivered", "returned"], "delivered": ["returned"], "cancelled": [], "returned": ["refunded"], "refunded": [] } def transition_to(self, new_state): if new_state in self.transitions.get(self.state, []): old_state = self.state self.state = new_state return { "success": True, "message": f"Order transitioned from {old_state} to {new_state}", "previous_state": old_state, "current_state": new_state } else: return { "success": False, "message": f"Invalid transition from {self.state} to {new_state}", "valid_transitions": self.transitions.get(self.state, []) }

Validation chain pattern

def validate_user_registration(user_data): validators = [ ("username", validate_username), ("email", validate_email), ("password", validate_password), ("age", validate_age), ("terms_accepted", validate_terms) ] errors = {} for field, validator in validators: if field in user_data: validation_result = validator(user_data[field]) if not validation_result["valid"]: errors[field] = validation_result["message"] else: errors[field] = f"{field} is required" return { "valid": len(errors) == 0, "errors": errors, "data": user_data if len(errors) == 0 else None }

def validate_username(username): if len(username) < 3: return {"valid": False, "message": "Username must be at least 3 characters"} elif len(username) > 20: return {"valid": False, "message": "Username must be less than 20 characters"} elif not username.isalnum(): return {"valid": False, "message": "Username must contain only letters and numbers"} else: return {"valid": True, "message": "Username is valid"}

def validate_email(email): if "@" not in email: return {"valid": False, "message": "Email must contain @ symbol"} elif "." not in email.split("@")[1]: return {"valid": False, "message": "Email domain must contain a dot"} else: return {"valid": True, "message": "Email format is valid"} `

Error Handling with Conditions {#error-handling}

Defensive Programming Patterns

`python

Comprehensive error handling with conditions

def safe_divide_with_conditions(dividend, divisor, precision=2): # Type checking if not isinstance(dividend, (int, float)): return { "success": False, "error": "TypeError", "message": f"Dividend must be a number, got {type(dividend).__name__}", "result": None } if not isinstance(divisor, (int, float)): return { "success": False, "error": "TypeError", "message": f"Divisor must be a number, got {type(divisor).__name__}", "result": None } # Value checking if divisor == 0: return { "success": False, "error": "ZeroDivisionError", "message": "Cannot divide by zero", "result": None } # Precision validation if not isinstance(precision, int) or precision < 0: return { "success": False, "error": "ValueError", "message": "Precision must be a non-negative integer", "result": None } # Perform calculation try: result = dividend / divisor rounded_result = round(result, precision) return { "success": True, "error": None, "message": "Division completed successfully", "result": rounded_result, "exact_result": result } except Exception as e: return { "success": False, "error": type(e).__name__, "message": f"Unexpected error during calculation: {str(e)}", "result": None }

File processing with comprehensive error handling

def process_data_file(filename, required_columns=None): import os # File existence check if not os.path.exists(filename): return { "success": False, "error": "FileNotFoundError", "message": f"File '{filename}' does not exist", "data": None } # File permission check if not os.access(filename, os.R_OK): return { "success": False, "error": "PermissionError", "message": f"No read permission for file '{filename}'", "data": None } # File size check (example: limit to 10MB) file_size = os.path.getsize(filename) if file_size > 10 1024 1024: # 10MB in bytes return { "success": False, "error": "FileSizeError", "message": f"File too large: {file_size / (1024*1024):.2f}MB (max: 10MB)", "data": None } try: with open(filename, 'r', encoding='utf-8') as file: lines = file.readlines() # Empty file check if not lines: return { "success": False, "error": "EmptyFileError", "message": "File is empty", "data": None } # Process header if required columns specified if required_columns: header = lines[0].strip().split(',') missing_columns = [col for col in required_columns if col not in header] if missing_columns: return { "success": False, "error": "MissingColumnsError", "message": f"Missing required columns: {missing_columns}", "data": None } # Process data processed_data = [] for line_num, line in enumerate(lines[1:], 2): # Skip header if line.strip(): # Skip empty lines data_row = line.strip().split(',') processed_data.append({ 'line_number': line_num, 'data': data_row }) return { "success": True, "error": None, "message": f"Successfully processed {len(processed_data)} data rows", "data": processed_data, "metadata": { "filename": filename, "file_size": file_size, "total_lines": len(lines), "data_rows": len(processed_data) } } except UnicodeDecodeError: return { "success": False, "error": "UnicodeDecodeError", "message": "File encoding is not UTF-8 compatible", "data": None } except Exception as e: return { "success": False, "error": type(e).__name__, "message": f"Unexpected error reading file: {str(e)}", "data": None } `

This comprehensive guide covers all aspects of using if-else conditions in Python, from basic syntax to advanced patterns and best practices. The examples demonstrate real-world applications and provide a solid foundation for understanding conditional logic in Python programming.

Tags

  • boolean logic
  • code-structure
  • conditional statements
  • control flow
  • python basics

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 Conditions: Complete Guide &amp; Best Practices