Skip to content

Conditional Statements

🎯 Core Concept

Conditional Statements are programming constructs that allow programs to make decisions and execute different code blocks based on whether a condition is true or false. They enable programs to respond to different situations and input values.

🔄 Types of Conditional Statements

If Statement

Executes a block of code only if a condition is true.

# Python
age = 18
if age >= 18:
    print("You are eligible to vote")
// Java
int age = 18;
if (age >= 18) {
    System.out.println("You are eligible to vote");
}

If-Else Statement

Executes one block if the condition is true, another if false.

# Python
score = 85
if score >= 60:
    print("You passed!")
else:
    print("You failed. Try again!")
// Java
int score = 85;
if (score >= 60) {
    System.out.println("You passed!");
} else {
    System.out.println("You failed. Try again!");
}

If-Else If-Else Statement

Tests multiple conditions in sequence.

# Python
score = 85
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"Your grade is: {grade}")
// Java
int score = 85;
char grade;

if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else if (score >= 60) {
    grade = 'D';
} else {
    grade = 'F';
}

System.out.println("Your grade is: " + grade);

Nested If Statements

If statements inside other if statements.

# Python
age = 20
has_license = True

if age >= 18:
    if has_license:
        print("You can drive")
    else:
        print("Get a license first")
else:
    print("You're too young to drive")
// Java
int age = 20;
boolean hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        System.out.println("You can drive");
    } else {
        System.out.println("Get a license first");
    }
} else {
    System.out.println("You're too young to drive");
}

🎯 Conditional Operators

Comparison Operators

Used to compare values in conditions.

Operator Python Java Description
Equal == == Values are equal
Not Equal != != Values are not equal
Greater Than > > Left value greater than right
Less Than < < Left value less than right
Greater Equal >= >= Left value greater or equal
Less Equal <= <= Left value less or equal

Logical Operators

Combine multiple conditions.

Operator Python Java Description
AND and && Both conditions true
OR or || At least one condition true
NOT not ! Reverses condition
# Python logical operators
age = 25
has_license = True
good_vision = True

if age >= 18 and has_license and good_vision:
    print("You can drive")
// Java logical operators
int age = 25;
boolean hasLicense = true;
boolean goodVision = true;

if (age >= 18 && hasLicense && goodVision) {
    System.out.println("You can drive");
}

🎓 Academic Context

Exam Focus Points

  • Definition: Decision-making constructs in programming
  • Types: If, If-Else, If-Else If-Else, Nested If
  • Operators: Comparison and logical operators
  • Applications: Input validation, decision logic, branching

Viva Questions

  • What is the difference between if and if-else statements?
  • When would you use nested if statements?
  • What are logical operators and how are they used?
  • How do you check multiple conditions in a single if statement?

Mark Distribution

  • Short Answers: 2-3 marks (definitions, operators)
  • Long Questions: 5 marks (examples, nested conditions)
  • Practical: Writing conditional logic for problems

Common Exam Topics

  • Grade calculation programs
  • Age validation systems
  • Login authentication
  • Number classification (positive/negative/zero)
  • Leap year determination

💻 Professional Context

Best Practices

  1. Condition Clarity
  2. Keep conditions simple and readable
  3. Use meaningful variable names
  4. Avoid deeply nested conditions when possible

  5. Error Handling

  6. Always validate input before processing
  7. Handle edge cases and boundary conditions
  8. Provide meaningful error messages

  9. Code Organization

  10. Use early returns to reduce nesting
  11. Extract complex conditions to variables
  12. Consider using switch statements for many conditions

  13. Performance

  14. Order conditions from most likely to least likely
  15. Use short-circuit evaluation efficiently
  16. Avoid redundant condition checks

Professional Examples

# Professional conditional logic with validation
class UserAuthentication:
    def __init__(self):
        self.max_attempts = 3
        self.lockout_duration = 300  # 5 minutes

    def authenticate_user(self, username: str, password: str, 
                         account_locked: bool, failed_attempts: int) -> dict:
        """
        Authenticate user with comprehensive validation

        Returns: dict with status and message
        """
        # Input validation
        if not username or not password:
            return {"status": "error", "message": "Username and password required"}

        if len(username) < 3 or len(username) > 50:
            return {"status": "error", "message": "Invalid username length"}

        # Account status check
        if account_locked:
            return {"status": "error", "message": "Account temporarily locked"}

        # Attempt limit check
        if failed_attempts >= self.max_attempts:
            return {"status": "error", "message": "Too many failed attempts"}

        # Authentication logic (simplified)
        if self._verify_credentials(username, password):
            return {"status": "success", "message": "Authentication successful"}
        else:
            return {"status": "error", "message": "Invalid credentials"}

    def _verify_credentials(self, username: str, password: str) -> bool:
        """Simulate credential verification"""
        # In real implementation, this would check against database
        valid_credentials = {
            "admin": "secure123",
            "user": "password456"
        }
        return valid_credentials.get(username) == password
// Professional conditional logic with comprehensive validation
public class UserAuthentication {
    private final int maxAttempts = 3;
    private final int lockoutDuration = 300; // 5 minutes

    public AuthenticationResult authenticateUser(String username, String password, 
                                                boolean accountLocked, int failedAttempts) {
        // Input validation
        if (username == null || password == null || 
            username.trim().isEmpty() || password.trim().isEmpty()) {
            return new AuthenticationResult("error", 
                "Username and password required");
        }

        if (username.length() < 3 || username.length() > 50) {
            return new AuthenticationResult("error", 
                "Invalid username length");
        }

        // Account status check
        if (accountLocked) {
            return new AuthenticationResult("error", 
                "Account temporarily locked");
        }

        // Attempt limit check
        if (failedAttempts >= maxAttempts) {
            return new AuthenticationResult("error", 
                "Too many failed attempts");
        }

        // Authentication logic
        if (verifyCredentials(username, password)) {
            return new AuthenticationResult("success", 
                "Authentication successful");
        } else {
            return new AuthenticationResult("error", 
                "Invalid credentials");
        }
    }

    private boolean verifyCredentials(String username, String password) {
        // Simulate credential verification
        Map<String, String> validCredentials = new HashMap<>();
        validCredentials.put("admin", "secure123");
        validCredentials.put("user", "password456");

        return password.equals(validCredentials.get(username));
    }

    // Helper class for results
    public static class AuthenticationResult {
        private final String status;
        private final String message;

        public AuthenticationResult(String status, String message) {
            this.status = status;
            this.message = message;
        }

        // Getters
        public String getStatus() { return status; }
        public String getMessage() { return message; }
    }
}

🔀 Alternative Conditional Structures

Switch Statement (Java)

Alternative to multiple if-else if statements.

// Java switch statement
int dayOfWeek = 3;
String dayName;

switch (dayOfWeek) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    case 6:
        dayName = "Saturday";
        break;
    case 7:
        dayName = "Sunday";
        break;
    default:
        dayName = "Invalid day";
}

System.out.println("Day: " + dayName);

Match Statement (Python 3.10+)

Modern alternative to if-else if chains.

# Python match statement (Python 3.10+)
day_of_week = 3

match day_of_week:
    case 1:
        day_name = "Monday"
    case 2:
        day_name = "Tuesday"
    case 3:
        day_name = "Wednesday"
    case 4:
        day_name = "Thursday"
    case 5:
        day_name = "Friday"
    case 6:
        day_name = "Saturday"
    case 7:
        day_name = "Sunday"
    case _:
        day_name = "Invalid day"

print(f"Day: {day_name}")
  • Boolean Logic: Foundation of conditional statements
  • Control Flow: How programs execute statements
  • Short-Circuit Evaluation: Optimized logical operator evaluation
  • Ternary Operator: Compact conditional expression
  • Pattern Matching: Advanced conditional matching

This atomic content bridges academic conditional theory with professional programming practices, emphasizing proper validation and error handling in decision-making logic.