If-Else Statements - Making Decisions

If-else statements are like decision trees: 'IF it's raining, take an umbrella. ELSE, wear sunglasses.' Your program makes choices based on conditions.
Decision‑making is what makes programs intelligent. Without conditional statements, a program would run the same way every time, regardless of user input or changing data. Python provides `if`, `elif` (else if), and `else` to let your code choose different paths.

**Basic `if` statement:**
```python
if condition:
# code to run if condition is True
```
The condition is any expression that evaluates to `True` or `False`. If `True`, the indented block executes; if `False`, Python skips it.

**`if`-`else` statement:**
```python
if condition:
# runs when True
else:
# runs when False
```

**`if`-`elif`-`else` chain:**
```python
if condition1:
# condition1 is True
elif condition2:
# condition1 False, condition2 True
elif condition3:
# condition1 and condition2 False, condition3 True
else:
# all conditions False
```
You can have as many `elif` blocks as you need. The `else` block is optional.

**Comparison operators (used in conditions):**
- `==` equal to (don't confuse with `=` assignment)
- `!=` not equal to
- `>` greater than
- `<` less than
- `>=` greater than or equal to
- `<=` less than or equal to

**Logical operators (combine conditions):**
- `and` – both must be True
- `or` – at least one must be True
- `not` – reverses the truth value

Examples:
```python
if age >= 18 and age <= 65:
print("Working age")
if day == "Saturday" or day == "Sunday":
print("Weekend!")
if not is_raining:
print("No umbrella needed")
```

**Indentation matters!**
Python uses indentation (usually 4 spaces) to group code blocks. All lines under an `if` must be indented equally. Inconsistent indentation causes `IndentationError`.

**Common mistakes:**
- Using `=` instead of `==` in conditions (assigns a value instead of comparing).
- Forgetting the colon `:` at the end of `if`, `elif`, or `else`.
- Not indenting properly (mixing tabs and spaces).
- Using `elif` without a preceding `if`.
- Comparing strings with `==` but forgetting case sensitivity (`"hello" != "Hello"`).

**Nested conditionals:**
You can put an `if` statement inside another `if`. This is useful for checking multiple levels of conditions, but be careful not to make your code too deep (hard to read).

**Truthy and falsy values:**
In Python, many non‑boolean values act like `True` or `False` in conditions:
- Falsy: `0`, `0.0`, `None`, empty strings `""`, empty lists `[]`, empty dictionaries `{}`
- Truthy: everything else (non‑zero numbers, non‑empty strings, etc.)

Example: `if name:` checks if `name` is not an empty string.

**Real‑world applications:**
- User authentication (checking username/password)
- Input validation (checking if age is positive)
- Game logic (if health <= 0: game over)
- Menu systems (respond to user choice)
- Grade calculators (assign letter grade based on score)
- E‑commerce (apply discount if total > $100)

**Practice exercises:**
1. Write a program that asks for a number and prints "Positive", "Negative", or "Zero".
2. Ask for a user's score (0‑100) and print the letter grade (A: ≥90, B: ≥80, C: ≥70, D: ≥60, F: <60).
3. Ask for a year and print whether it's a leap year (divisible by 4, but not by 100 unless also divisible by 400).
4. Create a simple login system with a hardcoded username and password, giving up to 3 attempts.
5. Ask for two numbers and an operator (+, -, *, /), then perform the calculation and print the result (handle division by zero).
# ========== EXAMPLE 1: Basic if-else (Adult or Minor) ==========
print("=== Example 1: Age Check ===")
age = int(input("Enter your age: "))

if age >= 18:
    print("You are an adult!")
else:
    print("You are a minor!")
print()

# ========== EXAMPLE 2: Multiple Conditions with elif (Temperature) ==========
print("=== Example 2: Weather Advice ===")
temperature = float(input("Enter temperature in Celsius: "))

if temperature > 30:
    print("It's hot! Stay hydrated.")
elif temperature > 20:
    print("Nice weather!")
elif temperature > 10:
    print("It's cool. Wear a jacket.")
else:
    print("It's cold! Bundle up.")
print()

# ========== EXAMPLE 3: Password Check + Logical Operators (AND/OR) ==========
print("=== Example 3: Access Control with Multiple Checks ===")
password = input("Enter password: ")

if password == "python123":
    print("Access granted!")
else:
    print("Access denied!")

# Additional example: using logical operators
print("\n--- Logical Operators Demo ---")
score = int(input("Enter your test score (0-100): "))
attendance = int(input("Enter attendance percentage: "))

if score >= 85 and attendance >= 75:
    print("Excellent! You get an A and a certificate.")
elif score >= 70 or attendance >= 90:
    print("Good effort! You pass.")
else:
    print("Need improvement. Please study more.")

→ Run this code interactively