Python Conditional Statements

Python conditional statements enable your program to evaluate expressions and execute specific code blocks when certain conditions are met. The core Python conditional statements include the if statement, elif statement, and else statement, which work together to create logical decision-making structures in your code.

The if Statement in Python

The if statement is the most basic Python conditional statement. It executes a block of code only when a specified condition evaluates to True.

Syntax:

if condition:
# code to execute when condition is True

Example:

temperature = 25
if temperature > 20:
print("It's a warm day!")

In this example, the Python conditional statement checks if the temperature is greater than 20. Since 25 > 20 is True, the message “It’s a warm day!” will be printed.

The else Statement in Python

The else statement works in conjunction with the if statement in Python conditional statements. It executes when the if condition evaluates to False.

Syntax:

if condition:
# code when condition is True
else:
# code when condition is False

Example:

age = 16
if age >= 18:
print("You can vote!")
else:
print("You cannot vote yet.")

This Python conditional statement checks voting eligibility. Since 16 < 18, the else block executes, printing “You cannot vote yet.”

The elif Statement in Python

The elif (else if) statement allows you to check multiple conditions in Python conditional statements. It’s evaluated only if the previous if or elif conditions are False.

Syntax:

if condition1:
# code when condition1 is True
elif condition2:
# code when condition2 is True
else:
# code when all conditions are False

Example:

score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")

This Python conditional statement evaluates multiple grade ranges. Since score is 85, it matches the second elif condition (score >= 80), printing “Grade: B”.

Comparison Operators in Python Conditional Statements

Python conditional statements rely heavily on comparison operators to evaluate conditions. Understanding these operators is crucial for writing effective conditional logic.

Equality and Inequality Operators

Equal to (==):

name = "Alice"
if name == "Alice":
print("Hello, Alice!")

Not equal to (!=):

status = "inactive"
if status != "active":
print("Account is not active")

Relational Operators

Greater than (>):

price = 299
if price > 250:
print("Expensive item")

Less than (<):

inventory = 5
if inventory < 10:
print("Low stock alert")

Greater than or equal to (>=):

experience = 3
if experience >= 2:
print("Eligible for senior position")

Less than or equal to (<=):

attempts = 2
if attempts <= 3:
print("Attempts remaining")

Logical Operators in Python Conditional Statements

Logical operators allow you to combine multiple conditions in Python conditional statements, creating more complex decision-making logic.

The and Operator

The and operator requires all conditions to be True for the entire expression to be True.

Example:

username = "john123"
password = "secret456"
if len(username) >= 5 and len(password) >= 8:
print("Valid credentials format")
else:
print("Invalid credentials format")

The or Operator

The or operator requires at least one condition to be True for the entire expression to be True.

Example:

day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's weekend!")
else:
print("It's a weekday")

The not Operator

The not operator reverses the boolean value of a condition.

Example:

is_logged_in = False
if not is_logged_in:
print("Please log in to continue")
else:
print("Welcome back!")

Membership Operators in Python Conditional Statements

Membership operators (in and not in) are frequently used in Python conditional statements to check if a value exists within a sequence.

The in Operator

Example:

allowed_colors = ["red", "blue", "green", "yellow"]
user_choice = "blue"
if user_choice in allowed_colors:
print(f"{user_choice} is a valid color choice")

The not in Operator

Example:

banned_words = ["spam", "fake", "scam"]
message = "This is a legitimate offer"
if "spam" not in message.lower():
print("Message appears to be legitimate")

Identity Operators in Python Conditional Statements

Identity operators (is and is not) compare object identity rather than equality in Python conditional statements.

The is Operator

Example:

value = None
if value is None:
print("Value is not initialized")

The is not Operator

Example:

data = []
if data is not None:
print("Data object exists")

Nested Python Conditional Statements

Python conditional statements can be nested inside other conditional statements to create complex decision trees.

Example:

weather = "sunny"
temperature = 28
if weather == "sunny":
if temperature > 25:
print("Perfect day for swimming!")
else:
print("Nice day for a walk")
else:
print("Indoor activities recommended")

Ternary Operator in Python Conditional Statements

Python offers a concise way to write simple conditional statements using the ternary operator (conditional expression).

Syntax:

value_if_true if condition else value_if_false

Example:

age = 20
status = "adult" if age >= 18 else "minor"
print(f"Person is an {status}")

Short-Circuit Evaluation in Python Conditional Statements

Python conditional statements use short-circuit evaluation, which means the evaluation stops as soon as the result is determined.

Example with and:

x = 0
if x != 0 and 10 / x > 5:
print("Condition met")
else:
print("Condition not met")

Example with or:

name = ""
if name or "Anonymous":
print("User identified")

Complete Example: Student Grade Calculator

Here’s a comprehensive example that demonstrates various Python conditional statements concepts:

# Student Grade Calculator using Python Conditional Statements

def calculate_grade(student_name, math_score, science_score, english_score):
"""
Calculate student grade using Python conditional statements
"""

# Input validation using conditional statements
if not student_name or not student_name.strip():
return "Error: Student name is required"

# Check if scores are valid
scores = [math_score, science_score, english_score]
for score in scores:
if not isinstance(score, (int, float)) or score < 0 or score > 100:
return "Error: All scores must be numbers between 0 and 100"

# Calculate average
average = (math_score + science_score + english_score) / 3

# Determine grade using nested conditional statements
if average >= 90:
grade = "A+"
message = "Excellent performance!"
elif average >= 85:
grade = "A"
message = "Outstanding work!"
elif average >= 80:
grade = "B+"
message = "Very good performance!"
elif average >= 75:
grade = "B"
message = "Good work!"
elif average >= 70:
grade = "C+"
message = "Satisfactory performance"
elif average >= 65:
grade = "C"
message = "Needs improvement"
elif average >= 60:
grade = "D"
message = "Below average performance"
else:
grade = "F"
message = "Failing grade - please seek help"

# Additional conditional checks
highest_score = max(math_score, science_score, english_score)
lowest_score = min(math_score, science_score, english_score)

# Check for subject-specific performance using logical operators
if math_score >= 90 and science_score >= 90 and english_score >= 90:
special_recognition = "🏆 All-Subject Excellence Award!"
elif highest_score - lowest_score > 30:
special_recognition = "⚠️ Significant variation in subject performance"
else:
special_recognition = "📊 Consistent performance across subjects"

# Scholarship eligibility using complex conditional statements
if average >= 85 and all(score >= 80 for score in scores):
scholarship_status = "✅ Eligible for Merit Scholarship"
elif average >= 75 and any(score >= 85 for score in scores):
scholarship_status = "🔍 Eligible for Subject-Specific Scholarship"
else:
scholarship_status = "❌ Not eligible for scholarships"

# Return formatted result
return f"""
=== STUDENT GRADE REPORT ===
Student: {student_name}

Individual Scores:
📐 Mathematics: {math_score}
🔬 Science: {science_score}
📚 English: {english_score}

Overall Performance:
📊 Average Score: {average:.2f}
🎯 Grade: {grade}
💬 Assessment: {message}

Additional Information:
🏅 Recognition: {special_recognition}
🎓 Scholarship: {scholarship_status}
"""

# Example usage and testing
if __name__ == "__main__":
# Test cases demonstrating various conditional statement scenarios

print("=== PYTHON CONDITIONAL STATEMENTS DEMO ===\n")

# Test Case 1: Excellent student
result1 = calculate_grade("Alice Johnson", 95, 92, 88)
print("Test Case 1 - Excellent Student:")
print(result1)

# Test Case 2: Average student
result2 = calculate_grade("Bob Smith", 78, 82, 75)
print("Test Case 2 - Average Student:")
print(result2)

# Test Case 3: Struggling student
result3 = calculate_grade("Charlie Brown", 45, 52, 48)
print("Test Case 3 - Struggling Student:")
print(result3)

# Test Case 4: Error handling
result4 = calculate_grade("", 85, 90, 78)
print("Test Case 4 - Error Handling:")
print(result4)

# Test Case 5: Invalid score
result5 = calculate_grade("Diana Prince", 105, 85, 90)
print("Test Case 5 - Invalid Score:")
print(result5)

# Demonstrate additional conditional statement features
print("\n=== ADDITIONAL CONDITIONAL STATEMENT EXAMPLES ===\n")

# Ternary operator example
students = ["Alice", "Bob", "Charlie", "Diana"]
for student in students:
status = "Present" if student in ["Alice", "Bob"] else "Absent"
print(f"{student}: {status}")

# Multiple condition checking
weather_conditions = {
"temperature": 22,
"humidity": 65,
"wind_speed": 15,
"is_raining": False
}

print(f"\nWeather Analysis:")
if weather_conditions["temperature"] > 20 and not weather_conditions["is_raining"]:
if weather_conditions["humidity"] < 70 and weather_conditions["wind_speed"] < 20:
print("🌞 Perfect weather for outdoor activities!")
else:
print("🌤️ Good weather with some considerations")
else:
print("🌧️ Indoor activities recommended")

Expected Output:

=== PYTHON CONDITIONAL STATEMENTS DEMO ===

Test Case 1 - Excellent Student:

=== STUDENT GRADE REPORT ===
Student: Alice Johnson

Individual Scores:
📐 Mathematics: 95
🔬 Science: 92
📚 English: 88

Overall Performance:
📊 Average Score: 91.67
🎯 Grade: A+
💬 Assessment: Excellent performance!

Additional Information:
🏅 Recognition: 📊 Consistent performance across subjects
🎓 Scholarship: ✅ Eligible for Merit Scholarship


Test Case 2 - Average Student:

=== STUDENT GRADE REPORT ===
Student: Bob Smith

Individual Scores:
📐 Mathematics: 78
🔬 Science: 82
📚 English: 75

Overall Performance:
📊 Average Score: 78.33
🎯 Grade: B
💬 Assessment: Good work!

Additional Information:
🏅 Recognition: 📊 Consistent performance across subjects
🎓 Scholarship: ❌ Not eligible for scholarships


Test Case 3 - Struggling Student:

=== STUDENT GRADE REPORT ===
Student: Charlie Brown

Individual Scores:
📐 Mathematics: 45
🔬 Science: 52
📚 English: 48

Overall Performance:
📊 Average Score: 48.33
🎯 Grade: F
💬 Assessment: Failing grade - please seek help

Additional Information:
🏅 Recognition: 📊 Consistent performance across subjects
🎓 Scholarship: ❌ Not eligible for scholarships


Test Case 4 - Error Handling:
Error: Student name is required

Test Case 5 - Invalid Score:
Error: All scores must be numbers between 0 and 100

=== ADDITIONAL CONDITIONAL STATEMENT EXAMPLES ===

Alice: Present
Bob: Present
Charlie: Absent
Diana: Absent

Weather Analysis:
🌞 Perfect weather for outdoor activities!

This comprehensive example demonstrates how Python conditional statements work together to create sophisticated decision-making logic. The code includes if statements, elif statements, else statements, nested conditionals, logical operators, and error handling—all essential components of effective Python conditional statements programming.