CodeSparks Logo

CodeSparks

PYTHON

10
CHAPTER
ACTIVE

Conditionals in Python

Conditionals are the foundation of decision-making in programming. They allow your programs to execute different code based on specific conditions, making your applications intelligent and responsive to various situations and user inputs.

What are Conditionals?

DEFINITION
Conditional Statement
A programming construct that performs different actions based on whether a condition is true or false. Conditionals enable programs to make decisions and branch into different execution paths.

Python uses indentation to define code blocks within conditional statements. This enforces clean, readable code structure and eliminates the need for curly braces found in other programming languages.

If Statements

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

PYTHON
# Basic if statement
age = 25

if age >= 18:
    print("You are an adult!")
    print("You can vote.")

# If statement with different conditions
temperature = 75

if temperature > 80:
    print("It's hot outside!")

score = 95

if score >= 90:
    print("Excellent work!")

# Multiple conditions using logical operators
username = "alice"
password = "secure123"

if username == "alice" and password == "secure123":
    print("Login successful!")

# If statements with different data types
items_in_cart = ["laptop", "mouse", "keyboard"]

if items_in_cart:  # Non-empty list is truthy
    print(f"You have {{len(items_in_cart)}} items in your cart")

if "laptop" in items_in_cart:
    print("Laptop found in cart")

# Checking for None
user_input = None

if user_input is not None:
    print("User provided input")

# Boolean variables in conditions
is_weekend = True
is_sunny = False

if is_weekend:
    print("Time to relax!")

if not is_sunny:
    print("Might need an umbrella")

If-Else Statements

The if-else statement provides an alternative path when the condition is false. This ensures your program always executes one of two possible code blocks.

PYTHON
# Basic if-else
age = 16

if age >= 18:
    print("You can vote!")
else:
    print("You cannot vote yet.")
    years_left = 18 - age
    print(f"You can vote in {{years_left}} years.")

# Number comparison
number = 7

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

# String comparison
user_response = input("Do you want to continue? (yes/no): ")

if user_response.lower() == "yes":
    print("Continuing...")
else:
    print("Operation cancelled.")

# Login validation
entered_password = "wrongpassword"
correct_password = "secret123"

if entered_password == correct_password:
    print("Access granted!")
    print("Welcome to the system.")
else:
    print("Access denied!")
    print("Incorrect password.")

# Grade evaluation
test_score = 73

if test_score >= 70:
    print("Congratulations! You passed.")
    print(f"Your score: {{test_score}}")
else:
    print("You need to retake the test.")
    points_needed = 70 - test_score
    print(f"You need {{points_needed}} more points to pass.")

# Shopping cart total
cart_total = 45.99
free_shipping_threshold = 50

if cart_total >= free_shipping_threshold:
    print("Congratulations! You qualify for free shipping.")
else:
    amount_needed = free_shipping_threshold - cart_total
    print(f"Add ${{amount_needed:.2f}} more for free shipping.")

Elif Statements

The elif (else if) statement allows you to check multiple conditions in sequence. Python evaluates conditions from top to bottom and executes the first matching condition.

PYTHON
# Grade letter assignment
score = 87

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

print(f"Score: {{score}}, Grade: {{grade}}")

# Weather recommendations
temperature = 65

if temperature > 85:
    print("It's very hot! Stay hydrated and find shade.")
elif temperature > 75:
    print("It's warm. Perfect weather for outdoor activities.")
elif temperature > 60:
    print("It's mild. A light jacket might be comfortable.")
elif temperature > 40:
    print("It's cool. You'll want to wear a jacket.")
elif temperature > 32:
    print("It's cold. Bundle up!")
else:
    print("It's freezing! Dress warmly and be careful.")

# User menu system
print("=== Main Menu ===")
print("1. View Profile")
print("2. Edit Settings")
print("3. Help")
print("4. Exit")

choice = input("Enter your choice (1-4): ")

if choice == "1":
    print("Displaying user profile...")
elif choice == "2":
    print("Opening settings menu...")
elif choice == "3":
    print("Opening help documentation...")
elif choice == "4":
    print("Goodbye!")
else:
    print("Invalid choice. Please select 1-4.")

# Age category classification
age = 25

if age < 0:
    print("Invalid age")
elif age < 2:
    print("Infant")
elif age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
elif age < 60:
    print("Adult")
else:
    print("Senior")

# BMI calculation and categorization
height = 1.75  # meters
weight = 70    # kilograms
bmi = weight / (height ** 2)

print(f"Your BMI is: {{bmi:.1f}}")

if bmi < 18.5:
    category = "Underweight"
elif bmi < 25:
    category = "Normal weight"
elif bmi < 30:
    category = "Overweight"
else:
    category = "Obese"

print(f"Category: {{category}}")

Nested Conditionals

Nested conditionals are if statements inside other if statements. They allow for complex decision-making logic but should be used carefully to maintain code readability.

PYTHON
# Nested conditionals for complex logic
age = 20
has_license = True
has_car = False

if age >= 18:
    print("You are an adult.")
    if has_license:
        print("You have a driver&apos;s license.")
        if has_car:
            print("You can drive your own car!")
        else:
            print("You can rent a car or borrow one.")
    else:
        print("You should get a driver&apos;s license.")
else:
    print("You are not old enough to drive.")

# Login system with multiple checks
username = "admin"
password = "secure123"
is_active = True

if username == "admin":
    print("Admin username recognized.")
    if password == "secure123":
        print("Password correct.")
        if is_active:
            print("Welcome, Administrator!")
            print("Full access granted.")
        else:
            print("Account is deactivated. Contact support.")
    else:
        print("Incorrect password for admin account.")
else:
    print("Username not found.")

# Academic eligibility checker
gpa = 3.2
credits_completed = 45
is_full_time = True

if gpa >= 2.0:
    print("GPA requirement met.")
    if credits_completed >= 30:
        print("Credit requirement met.")
        if is_full_time:
            print("Eligible for scholarship!")
        else:
            print("Must be full-time for scholarship.")
    else:
        credits_needed = 30 - credits_completed
        print(f"Need {{credits_needed}} more credits.")
else:
    print("GPA too low for eligibility.")

# Better approach: using logical operators instead of deep nesting
if gpa >= 2.0 and credits_completed >= 30 and is_full_time:
    print("Eligible for scholarship!")
elif gpa < 2.0:
    print("GPA too low for eligibility.")
elif credits_completed < 30:
    print(f"Need {{30 - credits_completed}} more credits.")
else:
    print("Must be full-time for scholarship.")

# Ticket pricing with multiple factors
age = 25
is_student = False
is_senior = False
day_of_week = "Saturday"

base_price = 12

if day_of_week in ["Saturday", "Sunday"]:
    print("Weekend pricing applies.")
    if age < 12:
        price = base_price * 0.5  # Child discount
    elif is_student:
        price = base_price * 0.8  # Student discount
    elif is_senior or age >= 65:
        price = base_price * 0.7  # Senior discount
    else:
        price = base_price
else:
    print("Weekday pricing applies.")
    price = base_price * 0.9  # Weekday discount

print(f"Ticket price: ${{price:.2f}}")
FUN FACT

Python is named after the British comedy group 'Monty Python's Flying Circus,' not the snake! Guido van Rossum was a fan of the show when he created the language, and he wanted a name that was short, unique, and slightly mysterious.

Why Learn Python?

Python has become the go-to language for millions of developers worldwide, and for good reason. Its versatility spans across industries and applications, making it one of the most valuable programming languages to learn in today's tech landscape.

FUN FACT

Python's indentation-based syntax makes nested conditionals visually clear, but deeply nested code can become hard to read. A good rule of thumb is to avoid more than 3-4 levels of nesting by using logical operators or separate functions instead.

Let's explore real-world applications of conditionals in practical programming scenarios that you might encounter in everyday development.

Conditional Expressions

Conditional expressions (ternary operators) provide a concise way to write simple if-else statements in a single line. They're perfect for simple assignments based on conditions.

PYTHON
# Basic conditional expression (ternary operator)
age = 20
status = "adult" if age >= 18 else "minor"
print(f"Status: {{status}}")

# Equivalent if-else statement
if age >= 18:
    status = "adult"
else:
    status = "minor"

# More examples of conditional expressions
temperature = 75
clothing = "shorts" if temperature > 70 else "pants"
print(f"Wear: {{clothing}}")

score = 85
result = "pass" if score >= 60 else "fail"
print(f"Test result: {{result}}")

# Using conditional expressions in function calls
def greet(name, formal=False):
    greeting = "Good day" if formal else "Hey"
    return f"{{greeting}}, {{name}}!"

print(greet("Alice", True))   # Good day, Alice!
print(greet("Bob", False))    # Hey, Bob!

# Conditional expressions with calculations
x = 10
y = 5
larger = x if x > y else y
print(f"Larger number: {{larger}}")

# Maximum of three numbers using nested conditional expressions
a, b, c = 15, 8, 12
maximum = a if a > b and a > c else b if b > c else c
print(f"Maximum: {{maximum}}")

# More readable approach for complex conditions
maximum = a if (a > b and a > c) else (b if b > c else c)

# Conditional expressions in list comprehensions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
categories = ["even" if num % 2 == 0 else "odd" for num in numbers]
print(f"Categories: {{categories}}")

# Default value assignment
user_input = ""
name = user_input if user_input else "Anonymous"
print(f"Hello, {{name}}!")

# Conditional expressions with method calls
text = "  Python Programming  "
cleaned = text.strip() if text else ""
print(f"Cleaned text: '{{cleaned}}'")

# Multiple conditional expressions
hour = 14
time_of_day = "morning" if hour < 12 else "afternoon" if hour < 17 else "evening"
print(f"It&apos;s {{time_of_day}}")

# When NOT to use conditional expressions (too complex)
# Bad: hard to read
result = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"

# Better: use regular if-elif-else for complex logic
if score >= 90:
    result = "A"
elif score >= 80:
    result = "B"
elif score >= 70:
    result = "C"
else:
    result = "F"

Practical Examples

Let's explore real-world applications of conditionals in practical programming scenarios that you might encounter in everyday development.

PYTHON
# Password strength checker
def check_password_strength(password):
    """Check password strength and provide feedback."""
    if len(password) < 8:
        return "Weak: Password must be at least 8 characters"
    elif len(password) < 12:
        if any(c.isdigit() for c in password) and any(c.isupper() for c in password):
            return "Good: Consider adding special characters"
        else:
            return "Fair: Add numbers and uppercase letters"
    else:
        has_digit = any(c.isdigit() for c in password)
        has_upper = any(c.isupper() for c in password)
        has_special = any(c in "!@#$%^&*" for c in password)
        
        if has_digit and has_upper and has_special:
            return "Strong: Excellent password!"
        else:
            return "Good: Consider adding missing elements"

# Test password checker
passwords = ["123", "password", "Password1", "MyStr0ng!Pass"]
for pwd in passwords:
    print(f"'{{pwd}}': {{check_password_strength(pwd)}}")

# Shopping cart discount calculator
def calculate_total(cart_value, customer_type="regular", coupon_code=None):
    """Calculate total with discounts applied."""
    discount = 0
    
    # Customer type discounts
    if customer_type == "premium":
        discount += 0.15
    elif customer_type == "student":
        discount += 0.10
    
    # Volume discounts
    if cart_value > 200:
        discount += 0.05
    elif cart_value > 100:
        discount += 0.02
    
    # Coupon codes
    if coupon_code == "SAVE20":
        discount += 0.20
    elif coupon_code == "WELCOME10":
        discount += 0.10
    
    # Apply discount (max 30%)
    final_discount = min(discount, 0.30)
    final_total = cart_value * (1 - final_discount)
    
    return final_total, final_discount

# Test discount calculator
cart = 150
customer = "premium"
coupon = "SAVE20"
total, discount = calculate_total(cart, customer, coupon)
print(f"Cart: ${{cart}}, Discount: {{discount:.1%}}, Total: ${{total:.2f}}")

# File processing based on extension
def process_file(filename):
    """Process file based on its extension."""
    if filename.endswith('.txt'):
        print(f"Processing text file: {{filename}}")
        return "text"
    elif filename.endswith('.csv'):
        print(f"Processing CSV file: {{filename}}")
        return "spreadsheet"
    elif filename.endswith(('.jpg', '.png', '.gif')):
        print(f"Processing image file: {{filename}}")
        return "image"
    elif filename.endswith(('.mp4', '.avi', '.mov')):
        print(f"Processing video file: {{filename}}")
        return "video"
    else:
        print(f"Unknown file type: {{filename}}")
        return "unknown"

# Test file processor
files = ["data.csv", "photo.jpg", "movie.mp4", "document.txt", "archive.zip"]
for file in files:
    process_file(file)

# Game character stats validator
def validate_character(stats):
    """Validate RPG character statistics."""
    name, level, health, mana = stats
    
    if not name or len(name.strip()) == 0:
        return False, "Character must have a name"
    
    if level < 1 or level > 100:
        return False, "Level must be between 1 and 100"
    
    if health <= 0:
        return False, "Health must be positive"
    
    if level <= 10 and health > 100:
        return False, "Low-level characters cannot have high health"
    
    if level > 50 and mana < 50:
        return False, "High-level characters need sufficient mana"
    
    return True, "Character is valid"

# Test character validator
characters = [
    ("Hero", 25, 150, 80),
    ("", 10, 50, 20),
    ("Warrior", 5, 200, 10),
    ("Mage", 60, 120, 30)
]

for char in characters:
    valid, message = validate_character(char)
    print(f"{{char[0] or 'Unnamed'}}: {{message}}")

# Smart thermostat logic
def thermostat_action(current_temp, target_temp, time_of_day, season):
    """Determine thermostat action based on multiple factors."""
    temp_diff = abs(current_temp - target_temp)
    
    # Tolerance based on time of day
    if time_of_day in ["night", "early_morning"]:
        tolerance = 3  # More tolerant at night
    else:
        tolerance = 2
    
    if temp_diff <= tolerance:
        return "maintain"
    
    # Determine heating or cooling
    if current_temp < target_temp:
        # Need heating
        if season == "winter":
            intensity = "high" if temp_diff > 5 else "medium"
        else:
            intensity = "low"
        return f"heat_{intensity}"
    else:
        # Need cooling
        if season == "summer":
            intensity = "high" if temp_diff > 5 else "medium"
        else:
            intensity = "low"
        return f"cool_{intensity}"

# Test thermostat
scenarios = [
    (68, 72, "morning", "winter"),
    (78, 75, "afternoon", "summer"),
    (70, 71, "night", "spring")
]

for current, target, time, season in scenarios:
    action = thermostat_action(current, target, time, season)
    print(f"Current: {{current}}&deg;F, Target: {{target}}&deg;F → Action: {{action}}")

Conditionals are the decision-making backbone of programming. They transform static code into dynamic, intelligent applications that respond appropriately to different situations. Master conditionals, and you'll be able to build programs that can handle complex logic and provide meaningful user experiences.