Chapter 5: If Statements

Conditionals let programs make decisions. Execute code only when conditions are met.

Boolean Expressions

Evaluate to True or False:

5 == 5   # True
5 == 6   # False
5 != 6   # True (not equal)
5 > 3    # True
5 >= 5   # True
5 < 3    # False
5 <= 5   # True

String Comparison

Case-sensitive by default:

'Python' == 'python'        # False
'Python'.lower() == 'python' # True

in Operator

Check membership:

servers = ['web-01', 'db-01', 'cache-01']
'web-01' in servers      # True
'app-01' in servers      # False
'app-01' not in servers  # True

Boolean Operators

Combine conditions:

age = 25

age >= 18 and age <= 65   # True (both must be true)
age < 18 or age > 65      # False (either can be true)
not age < 18              # True (inverts result)

Chained comparison (Pythonic):

18 <= age <= 65  # same as: age >= 18 and age <= 65

If Statements

Simple If

age = 20
if age >= 18:
    print("You can vote")

If-Else

age = 16
if age >= 18:
    print("You can vote")
else:
    print("Too young to vote")

If-Elif-Else

Multiple conditions, first match wins:

age = 25

if age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
elif age < 65:
    print("Adult")
else:
    print("Senior")

Multiple Elifs

status_code = 404

if status_code == 200:
    status = "OK"
elif status_code == 301:
    status = "Redirect"
elif status_code == 404:
    status = "Not Found"
elif status_code == 500:
    status = "Server Error"
else:
    status = "Unknown"

Optional Else

else isn’t required:

if status_code == 200:
    log("Success")
elif status_code >= 500:
    alert("Server error!")
# No else - do nothing for other codes

Testing Multiple Conditions

if-elif stops at first match. Use multiple if to test all:

# Only one runs
requested = ['ssh', 'http', 'https']
if 'ssh' in requested:
    print("Port 22")
elif 'http' in requested:
    print("Port 80")  # never runs

# All matching conditions run
if 'ssh' in requested:
    print("Port 22")
if 'http' in requested:
    print("Port 80")
if 'https' in requested:
    print("Port 443")

If with Lists

Check If List Is Empty

Empty list is falsy:

queue = []
if queue:
    print(f"Processing {len(queue)} items")
else:
    print("Queue empty")

Process Items Conditionally

servers = ['web-01', 'db-01', 'cache-01']

for server in servers:
    if server.startswith('web'):
        print(f"{server}: nginx")
    elif server.startswith('db'):
        print(f"{server}: postgres")
    else:
        print(f"{server}: unknown service")

Ternary Expression

One-line conditional assignment:

age = 20
status = "adult" if age >= 18 else "minor"

Useful for simple cases. Don’t nest them.

Truthy and Falsy

Python evaluates these as False: - False - None - 0, 0.0 - "" (empty string) - [], {}, () (empty collections)

Everything else is True:

name = ""
if name:
    print(f"Hello, {name}")
else:
    print("Name required")

items = []
if items:  # cleaner than: if len(items) > 0
    process(items)

Quick Reference

Operation Code

Equality

==, !=

Comparison

<, , >, >=

Membership

in, not in

Boolean ops

and, or, not

Chained

1 < x < 10

Conditional

if:, elif:, else:

Ternary

x if condition else y

Exercises

5-1. Conditional Tests

Write tests that evaluate to True and False: - String equality (case-sensitive and insensitive) - Numeric comparisons - in and not in - and / or combinations

5-2. Stages of Life

Write if-elif-else for age ranges: - < 2: baby - 2-4: toddler - 5-12: kid - 13-19: teenager - 20-64: adult - 65+: elder

5-3. Favorite Fruits

Create a list of favorite fruits. Check 5 fruits with if statements.

5-4. Usernames

Given a list of usernames: - If empty, print "We need users!" - Otherwise, greet each user - Special greeting for 'admin'

5-5. Ordinal Numbers

Print 1st through 9th using if-elif for special cases (1st, 2nd, 3rd).

Summary

  • Comparison operators: ==, !=, <, >, , >=

  • Boolean operators: and, or, not

  • in checks membership

  • if, elif, else for branching

  • Empty collections are falsy

  • Ternary: value if condition else other

Next: Dictionaries for key-value data.