Conditions in Python: My Decision-Making Guide¶
Author: Mohammad Sayem Chowdhury
Welcome! In this notebook, I'll share my journey understanding conditional statements in Python. Conditions are the backbone of decision-making in programming, and mastering them has been crucial for creating intelligent, responsive code. By the end, you'll see how I approach comparison operators, branching, and logical operations.
What I'll Cover¶
- Comparison Operators
- If, Elif, and Else Statements
- Logical Operators (and, or, not)
- Nested Conditions
- Practical Decision-Making Examples
Estimated time: about 20 minutes of logical exploration.
Comparison Operators: My Foundation¶
Comparison operators are how I make my programs smart. They compare values and return True or False, which becomes the basis for all decision-making:
- Equal:
==(checks if values are the same) - Not equal:
!=(checks if values are different) - Greater than:
> - Less than:
< - Greater than or equal:
>= - Less than or equal:
<=
# My personal data for examples
my_age = 25
my_height = 175 # in cm
my_name = "Mohammad Sayem Chowdhury"
my_gpa = 3.8
print("My information:")
print(f"Age: {my_age}")
print(f"Height: {my_height} cm")
print(f"Name: {my_name}")
print(f"GPA: {my_gpa}")
print()
# Testing equality
print("Equality comparisons:")
print(f"Is my age exactly 25? {my_age == 25}")
print(f"Is my name 'Mohammad'? {my_name == 'Mohammad'}")
print(f"Is my GPA exactly 4.0? {my_gpa == 4.0}")
print()
# Testing inequality
print("Inequality comparisons:")
print(f"Is my age not 30? {my_age != 30}")
print(f"Is my height not 180cm? {my_height != 180}")
# Numerical comparisons with my data
print("Numerical comparisons:")
print(f"Am I older than 20? {my_age > 20}")
print(f"Am I younger than 30? {my_age < 30}")
print(f"Is my height at least 170cm? {my_height >= 170}")
print(f"Is my GPA at most 4.0? {my_gpa <= 4.0}")
print()
# Comparing different data types
favorite_number = 7
lucky_number = "7"
print("Type comparison:")
print(f"Favorite number: {favorite_number} (type: {type(favorite_number)})")
print(f"Lucky number: {lucky_number} (type: {type(lucky_number)})")
print(f"Are they equal? {favorite_number == lucky_number}")
print(f"Are they equal after conversion? {favorite_number == int(lucky_number)}")
Branching: Making Decisions¶
This is where conditions become powerful! I use if, elif, and else to make my programs respond differently based on conditions:
# Simple if statement
current_hour = 14 # 2 PM in 24-hour format
if current_hour < 12:
greeting = "Good morning!"
print(greeting)
print(f"Current time: {current_hour}:00")
# If-else statement
temperature = 22 # Celsius
if temperature >= 25:
print("It's a warm day! Perfect for outdoor activities.")
outfit = "Light clothes"
else:
print("It's a cool day. Maybe stay indoors or dress warmly.")
outfit = "Warm clothes"
print(f"Temperature: {temperature}°C")
print(f"Recommended outfit: {outfit}")
# Multiple conditions with elif
def get_grade_feedback(score):
"""My grading system with personalized feedback."""
if score >= 90:
grade = 'A'
feedback = "Excellent work! You're mastering the material."
elif score >= 80:
grade = 'B'
feedback = "Good job! You have a solid understanding."
elif score >= 70:
grade = 'C'
feedback = "Fair work. Consider reviewing key concepts."
elif score >= 60:
grade = 'D'
feedback = "You're passing, but there's room for improvement."
else:
grade = 'F'
feedback = "Let's work together to improve your understanding."
return grade, feedback
# Testing my grading system
test_scores = [95, 87, 73, 65, 45]
for score in test_scores:
grade, feedback = get_grade_feedback(score)
print(f"Score: {score} | Grade: {grade} | {feedback}")
Logical Operators: Combining Conditions¶
I often need to combine multiple conditions. Python's logical operators help me create complex decision trees:
- and: Both conditions must be True
- or: At least one condition must be True
- not: Reverses the boolean value
# Personal eligibility checker
age = 25
has_degree = True
years_experience = 3
speaks_english = True
print("Checking job eligibility...")
print(f"Age: {age}")
print(f"Has degree: {has_degree}")
print(f"Years of experience: {years_experience}")
print(f"Speaks English: {speaks_english}")
print()
# Using 'and' operator
if age >= 18 and has_degree:
print("✓ Meets basic requirements (age and education)")
else:
print("✗ Does not meet basic requirements")
# Using 'or' operator
if years_experience >= 5 or has_degree:
print("✓ Meets experience/education requirement")
else:
print("✗ Needs more experience or education")
# Using 'not' operator
if not (age < 18):
print("✓ Is an adult")
else:
print("✗ Is a minor")
# Complex condition combining all operators
if (age >= 21 and has_degree) and (years_experience >= 2 or speaks_english):
print("✓ HIRED! Welcome to the team!")
else:
print("✗ Not quite there yet, but keep improving!")
# Weather decision system
temperature = 20
is_raining = False
is_weekend = True
have_umbrella = True
print("Weather Decision System")
print(f"Temperature: {temperature}°C")
print(f"Raining: {is_raining}")
print(f"Weekend: {is_weekend}")
print(f"Have umbrella: {have_umbrella}")
print()
# Decision making with multiple logical operators
if temperature > 25 and not is_raining:
activity = "Go to the beach or have a picnic"
elif temperature > 15 and (not is_raining or have_umbrella):
activity = "Take a walk in the park"
elif is_weekend and temperature > 10:
activity = "Visit a museum or go shopping"
else:
activity = "Stay home with a good book and hot tea"
print(f"Recommended activity: {activity}")
# Complex logical expression
perfect_day = (temperature >= 20 and temperature <= 28) and not is_raining and is_weekend
print(f"Is it a perfect day? {perfect_day}")
Nested Conditions: Advanced Decision Trees¶
Sometimes I need multiple levels of conditions for complex scenarios:
# Academic scholarship eligibility system
def check_scholarship_eligibility(gpa, family_income, extracurriculars, essay_score):
"""My scholarship evaluation system."""
print(f"Evaluating scholarship application:")
print(f"GPA: {gpa}")
print(f"Family Income: ${family_income:,}")
print(f"Extracurricular Activities: {extracurriculars}")
print(f"Essay Score: {essay_score}/100")
print()
if gpa >= 3.5:
print("✓ Academic requirement met (GPA ≥ 3.5)")
if family_income <= 50000:
print("✓ Financial need requirement met")
if extracurriculars >= 2:
print("✓ Extracurricular requirement met")
if essay_score >= 80:
scholarship = "Full Scholarship ($10,000)"
elif essay_score >= 70:
scholarship = "Partial Scholarship ($5,000)"
else:
scholarship = "Merit Award ($1,000)"
else:
print("✗ Insufficient extracurricular activities")
scholarship = "Merit Award ($1,000)" if essay_score >= 75 else "Not eligible"
elif family_income <= 100000:
print("• Moderate financial need")
if extracurriculars >= 3 and essay_score >= 85:
scholarship = "Partial Scholarship ($3,000)"
else:
scholarship = "Merit Award ($1,000)"
else:
print("• No financial need")
if extracurriculars >= 4 and essay_score >= 90:
scholarship = "Excellence Award ($2,000)"
else:
scholarship = "Recognition Certificate"
else:
print("✗ Academic requirement not met (GPA < 3.5)")
scholarship = "Not eligible"
return scholarship
# Test different scenarios
applicants = [
("Mohammad", 3.8, 35000, 3, 85),
("Sarah", 3.9, 75000, 4, 92),
("Ahmed", 3.2, 40000, 2, 80),
("Lisa", 3.6, 120000, 5, 95)
]
for name, gpa, income, activities, essay in applicants:
print(f"=== {name}'s Application ===")
result = check_scholarship_eligibility(gpa, income, activities, essay)
print(f"Result: {result}")
print("-" * 40)
Practical Applications: Real-World Examples¶
Let me show how I use conditions in everyday programming scenarios:
# Password strength validator
def validate_password(password):
"""My password strength checking system."""
score = 0
feedback = []
# Length check
if len(password) >= 8:
score += 1
feedback.append("✓ Length is adequate (8+ characters)")
else:
feedback.append("✗ Password too short (needs 8+ characters)")
# Uppercase check
if any(c.isupper() for c in password):
score += 1
feedback.append("✓ Contains uppercase letters")
else:
feedback.append("✗ Needs uppercase letters")
# Lowercase check
if any(c.islower() for c in password):
score += 1
feedback.append("✓ Contains lowercase letters")
else:
feedback.append("✗ Needs lowercase letters")
# Number check
if any(c.isdigit() for c in password):
score += 1
feedback.append("✓ Contains numbers")
else:
feedback.append("✗ Needs numbers")
# Special character check
special_chars = "!@#$%^&*()_+-=[]{}|;:,.<>?"
if any(c in special_chars for c in password):
score += 1
feedback.append("✓ Contains special characters")
else:
feedback.append("✗ Needs special characters")
# Determine strength
if score >= 5:
strength = "Very Strong"
elif score >= 4:
strength = "Strong"
elif score >= 3:
strength = "Moderate"
elif score >= 2:
strength = "Weak"
else:
strength = "Very Weak"
return strength, score, feedback
# Test different passwords
test_passwords = [
"password123",
"MySecureP@ss123",
"weakpw",
"StrongPassword2024!",
"12345678"
]
for pwd in test_passwords:
strength, score, feedback = validate_password(pwd)
print(f"Password: {'*' * len(pwd)} (length: {len(pwd)})")
print(f"Strength: {strength} ({score}/5)")
for comment in feedback:
print(f" {comment}")
print("-" * 50)
# Personal budget tracker with conditions
def analyze_spending(income, expenses):
"""My personal finance analysis system."""
total_expenses = sum(expenses.values())
savings = income - total_expenses
savings_rate = (savings / income) * 100 if income > 0 else 0
print(f"Monthly Income: ${income:,.2f}")
print(f"Total Expenses: ${total_expenses:,.2f}")
print(f"Savings: ${savings:,.2f}")
print(f"Savings Rate: {savings_rate:.1f}%")
print()
# Financial health assessment
if savings_rate >= 20:
status = "Excellent"
advice = "Great job! You're building a strong financial foundation."
elif savings_rate >= 10:
status = "Good"
advice = "You're doing well! Consider increasing savings gradually."
elif savings_rate >= 5:
status = "Fair"
advice = "You're saving something, but try to reduce unnecessary expenses."
elif savings_rate > 0:
status = "Poor"
advice = "Your savings are minimal. Review your budget carefully."
else:
status = "Critical"
advice = "You're spending more than you earn. Immediate action needed!"
print(f"Financial Status: {status}")
print(f"Advice: {advice}")
print()
# Expense category analysis
print("Expense Analysis:")
for category, amount in expenses.items():
percentage = (amount / income) * 100
if percentage > 30:
flag = "⚠️ HIGH"
elif percentage > 20:
flag = "⚡ MODERATE"
else:
flag = "✅ NORMAL"
print(f"{category}: ${amount:,.2f} ({percentage:.1f}%) {flag}")
# My monthly budget
my_income = 5000
my_expenses = {
"Rent": 1200,
"Food": 600,
"Transportation": 300,
"Utilities": 200,
"Entertainment": 400,
"Savings_Investment": 1000,
"Miscellaneous": 200
}
analyze_spending(my_income, my_expenses)
# Smart home automation system
def smart_home_controller(time_hour, temperature, occupancy, day_of_week):
"""My smart home decision system."""
actions = []
# Lighting control
if occupancy and (time_hour < 7 or time_hour > 18):
actions.append("Turn on lights")
elif not occupancy or (7 <= time_hour <= 18):
actions.append("Turn off lights")
# Heating/cooling control
if occupancy:
if temperature < 20:
actions.append("Turn on heating to 22°C")
elif temperature > 26:
actions.append("Turn on AC to 24°C")
else:
actions.append("Maintain current temperature")
else:
if temperature < 16:
actions.append("Set heating to 18°C (energy saving)")
elif temperature > 28:
actions.append("Set AC to 26°C (energy saving)")
else:
actions.append("Turn off climate control")
# Security system
if not occupancy and (time_hour < 6 or time_hour > 22):
actions.append("Activate full security mode")
elif not occupancy:
actions.append("Activate basic security mode")
else:
actions.append("Deactivate security system")
# Weekend special rules
if day_of_week in [6, 7]: # Weekend
if occupancy and 8 <= time_hour <= 10:
actions.append("Play relaxing music")
if time_hour == 19: # 7 PM
actions.append("Dim lights for movie time")
return actions
# Simulate different scenarios
scenarios = [
("Monday 8AM", 8, 18, True, 1),
("Tuesday 2PM", 14, 24, False, 2),
("Friday 7PM", 19, 22, True, 5),
("Saturday 9AM", 9, 19, True, 6),
("Sunday 11PM", 23, 25, False, 7)
]
for desc, hour, temp, occupied, day in scenarios:
print(f"=== {desc} ===")
print(f"Temperature: {temp}°C, Occupied: {occupied}")
actions = smart_home_controller(hour, temp, occupied, day)
for action in actions:
print(f"• {action}")
print()
My Key Takeaways¶
Mastering conditions has transformed how I write Python code. Here's what I consider most important:
- Comparison Operators: The foundation of all decision-making in code
- Logical Operators: Enable complex, multi-factor decisions
- Nested Conditions: Allow sophisticated decision trees for complex scenarios
- Clean Structure: Well-organized if-elif-else chains make code readable
- Real-World Applications: Conditions are everywhere - from validation to automation
I use conditions for:
- Input validation and error checking
- User authentication and authorization
- Data filtering and categorization
- Business logic implementation
- Automated decision systems
- Game development and interactive applications
The key is to think logically about decision-making and translate that into clear, readable conditional statements.
Copyright © 2025 Mohammad Sayem Chowdhury. This notebook and its content are shared for personal learning and inspiration.
Next Steps in My Conditional Logic Journey¶
Understanding conditions opened the door to loops, functions, and object-oriented programming. Every advanced Python concept builds on this foundation of logical decision-making.
— Mohammad Sayem Chowdhury