Python Conditional Statements

· Seokhyeon Byun

Note: This post is based on my old programming study notes when I taught myself.

Basic Syntax

if condition_1:
    Statement_1
    
elif condition_2:
    Statement_2
    
else:
    Statement_3

If condition_1 is True, then execute Statement_1. If both condition_1 and condition_2 are False, then execute Statement_3. elif can be used multiple times if required.

Important Notes

  • Always be careful with indentation - Python uses indentation to define code blocks
  • Colon at the end of condition - Each condition line must end with :
# Example
age = 18

if age >= 18:
    print("You are an adult")
elif age >= 13:
    print("You are a teenager")
else:
    print("You are a child")

Comparison Operators

OperatorDescription
x < yLess than
x > yGreater than
x == yEqual to
x != yNot equal to
x >= yGreater than or equal to
x <= yLess than or equal to
# Examples
score = 85

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

Logical Operators

and, or, not

OperatorDescription
x and yBoth x and y are True, then True
x or yEither x or y is True, then True
not xIf x is False, then True
# Examples
temperature = 75
sunny = True

if temperature > 70 and sunny:
    print("Perfect weather for a picnic!")
    
if temperature < 32 or temperature > 100:
    print("Extreme weather conditions")
    
if not sunny:
    print("Don't forget your umbrella")

Membership Operators

in, not in

  • x in [List/Tuple/String]
  • x not in [List/Tuple/String]
# Examples
fruits = ['apple', 'banana', 'orange']
favorite = 'apple'

if favorite in fruits:
    print("Your favorite fruit is available")
    
if 'grape' not in fruits:
    print("We don't have grapes")

# String membership
text = "Hello World"
if 'World' in text:
    print("Found 'World' in the text")

pass Statement

When we want “Nothing to happen for a certain condition”, use pass.

names = ['Bruce', 'James', 'Bobby', 'Jessica']

if 'Jessica' in names:
    pass  # Do nothing
else:
    print('There is a stranger in our crew.')

Explanation: If Jessica is in the names list, then nothing happens. If the name is not in the list, execute the else part.

# Another example - placeholder for future code
def process_data(data):
    if len(data) > 100:
        pass  # TODO: Implement optimization for large datasets
    else:
        print("Processing small dataset")

One-line if Statement

If the statement after condition is just one line, we can write the if condition and statement on one line.

pocket = ['iPhone', 'money', 'apple']

if 'money' in pocket: pass
else: print("Show me your money")

# More practical examples
age = 20
print("Adult") if age >= 18 else print("Minor")

# Or with variables
status = "eligible" if age >= 18 else "not eligible"

Conditional Expression (Ternary Operator)

Traditional way:

if score >= 90:
    message = "Pass"
else:
    message = "Fail"

Using conditional expression:

message = "Pass" if score >= 90 else "Fail"

More examples:

# Determine absolute value
number = -5
absolute = number if number >= 0 else -number

# Set default value
username = input_name if input_name else "Anonymous"

# Choose maximum
maximum = a if a > b else b

# Nested conditional expressions
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"

Common Patterns

Multiple Conditions

# AND conditions
if age >= 18 and has_license and has_insurance:
    print("You can drive")

# OR conditions  
if payment_method == "cash" or payment_method == "card" or payment_method == "digital":
    print("Payment accepted")

# Better way for OR with multiple values
if payment_method in ["cash", "card", "digital"]:
    print("Payment accepted")

Range Checking

# Check if number is in range
number = 75
if 0 <= number <= 100:
    print("Number is within valid range")

# Grade boundaries
if 90 <= score <= 100:
    grade = "A"
elif 80 <= score < 90:
    grade = "B"
elif 70 <= score < 80:
    grade = "C"

Truthy and Falsy Values

# These evaluate to False
empty_list = []
empty_string = ""
zero = 0
none_value = None

if not empty_list:
    print("List is empty")

# These evaluate to True
non_empty_list = [1, 2, 3]
non_empty_string = "hello"
non_zero = 42

if non_empty_list:
    print("List has items")

---

## **Technical Interview Essentials**

### Short-Circuit Evaluation

**Critical Interview Knowledge:**
```python
# and operator - stops at first False value
def expensive_operation():
    print("This is expensive!")
    return True

x = False
result = x and expensive_operation()  # expensive_operation() is NOT called!

# or operator - stops at first True value
y = True  
result = y or expensive_operation()   # expensive_operation() is NOT called!

# Practical example - safe attribute access
user = None
# This would crash: print(user.name)
# Safe way using short-circuit:
print("Unknown" if not user else user.name)

Chained Comparisons

Python’s Unique Feature:

# Python allows chained comparisons (most languages don't)
age = 25
is_adult = 18 <= age < 65  # Much cleaner than: age >= 18 and age < 65

# Multiple comparisons
score = 85
valid_score = 0 <= score <= 100

# Watch out for logical errors
# This is WRONG: if score == 90 or 95 or 100:  # Always True!
# CORRECT:
if score in [90, 95, 100]:
    print("Excellent score!")

Common Interview Patterns

1. FizzBuzz Pattern (Classic Interview Question)

def fizzbuzz(n):
    """
    Print numbers 1 to n, but:
    - "Fizz" for multiples of 3
    - "Buzz" for multiples of 5  
    - "FizzBuzz" for multiples of both
    """
    result = []
    for i in range(1, n + 1):
        if i % 15 == 0:  # Check 15 first (3*5)
            result.append("FizzBuzz")
        elif i % 3 == 0:
            result.append("Fizz")
        elif i % 5 == 0:
            result.append("Buzz")
        else:
            result.append(str(i))
    return result

# Alternative using ternary operators
def fizzbuzz_compact(n):
    return [
        "FizzBuzz" if i % 15 == 0 else
        "Fizz" if i % 3 == 0 else  
        "Buzz" if i % 5 == 0 else str(i)
        for i in range(1, n + 1)
    ]

2. Input Validation Pattern

def validate_email(email):
    """Validate email format - common interview task"""
    if not email or not isinstance(email, str):
        return False, "Email must be a non-empty string"
    
    if "@" not in email:
        return False, "Email must contain @"
    
    parts = email.split("@")
    if len(parts) != 2:
        return False, "Email must have exactly one @"
    
    local, domain = parts
    if not local or not domain:
        return False, "Email must have local and domain parts"
    
    if "." not in domain:
        return False, "Domain must contain at least one dot"
    
    return True, "Valid email"

# Test cases
test_emails = ["user@domain.com", "invalid", "@domain.com", "user@"]
for email in test_emails:
    valid, message = validate_email(email)
    print(f"{email:<15} -> {message}")

3. Number Classification

def classify_number(n):
    """Classify number properties - tests multiple conditions"""
    if not isinstance(n, (int, float)):
        return "Not a number"
    
    properties = []
    
    # Basic sign
    if n > 0:
        properties.append("positive")
    elif n < 0:
        properties.append("negative")
    else:
        properties.append("zero")
    
    # Integer properties
    if isinstance(n, int) and n != 0:
        if n % 2 == 0:
            properties.append("even")
        else:
            properties.append("odd")
        
        # Prime check for small numbers
        if n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1)):
            properties.append("prime")
    
    # Range classifications
    if abs(n) < 10:
        properties.append("single-digit")
    elif abs(n) < 100:
        properties.append("double-digit")
    
    return ", ".join(properties)

# Test
print(classify_number(17))   # "positive, odd, prime, double-digit"
print(classify_number(-4))   # "negative, even, single-digit"

Common Interview Gotchas

1. Assignment vs Comparison

# WRONG - assignment instead of comparison
x = 5
if x = 10:  # SyntaxError in Python!
    print("This won't work")

# Python prevents this error, but watch out in other languages
# CORRECT:
if x == 10:
    print("This works")

2. Boolean Identity vs Equality

# Be careful with True/False comparisons
x = 1

# These are different!
print(x == True)   # True (1 equals True)  
print(x is True)   # False (1 is not the same object as True)

# Better practice - rely on truthiness
if x:              # Pythonic way
    print("x is truthy")

# Watch out for this interview trap:
if x == True:      # Works but not pythonic
    print("x equals True")

3. Mutable Default Arguments in Conditions

def process_items(items=None):
    """Safe way to handle mutable defaults"""
    if items is None:
        items = []  # Create new list each time
    
    # Process items...
    return items

# Common mistake that can cause bugs:
def bad_function(items=[]):  # DON'T DO THIS!
    items.append("new item")  # Modifies the default!
    return items

Performance Considerations

1. Condition Ordering

# Order conditions by likelihood (most common first)
def categorize_user(user):
    # If most users are 'regular', check this first
    if user.type == 'regular':
        return "Standard user"
    elif user.type == 'premium':  
        return "Premium user"
    elif user.type == 'admin':     # Least common, check last
        return "Administrator"
    else:
        return "Unknown user type"

# For complex conditions, check cheapest operations first
def expensive_check():
    print("This takes time...")
    return True

def cheap_check():
    return False

# Good - cheap check first
if cheap_check() and expensive_check():
    print("Both conditions met")

2. Dictionary-Based Dispatch (Alternative to Long if-elif chains)

# Instead of long if-elif chains:
def handle_command_slow(command):
    if command == "start":
        return "Starting system..."
    elif command == "stop":
        return "Stopping system..."
    elif command == "restart":
        return "Restarting system..."
    # ... many more conditions

# Use dictionary dispatch (faster for many conditions):
def handle_command_fast(command):
    handlers = {
        "start": lambda: "Starting system...",
        "stop": lambda: "Stopping system...",
        "restart": lambda: "Restarting system...",
        # ... many more handlers
    }
    
    handler = handlers.get(command)
    if handler:
        return handler()
    else:
        return f"Unknown command: {command}"

Edge Cases to Remember

# 1. Empty string is falsy
name = ""
if name:  # False
    print("Has name")

# 2. Zero is falsy (including 0.0)
count = 0
if count:  # False
    print("Has items")

# 3. Empty containers are falsy
if []:      # False
    print("List has items")

if {}:      # False  
    print("Dict has items")

# 4. None is falsy
value = None
if value:   # False
    print("Has value")

# 5. Be explicit when you need to check for specific values
if count == 0:      # Explicitly check for zero
    print("Count is exactly zero")

if name == "":      # Explicitly check for empty string
    print("Name is empty string")