Files
labs/Lab-2/Lab-2-Solution/02_Control_Flow_Functions_Solution.ipynb

5.5 KiB

Module 2 — Lab 2: Control Flow and Functions

Topics: if/elif/else, for, while, break, continue, function

Solution version: This notebook contains the complete solution. Run the cells in order and compare the results with your Lab notebook.

Scenario

You need to build small rules that classify login alerts and automatically review a list of IP addresses. All activity is simulated with local data; this notebook does not connect to or scan any real system.

1. Classify failed login attempts

In [ ]:
failed_attempts = 7

if failed_attempts >= 10:
    severity = "CRITICAL"
elif failed_attempts >= 5:
    severity = "HIGH"
elif failed_attempts >= 1:
    severity = "MEDIUM"
else:
    severity = "LOW"

print(severity)

2. Review IP addresses with for, continue, and break

In [ ]:
blocked_ips = {"10.0.0.5", "10.0.0.12"}
targets = [f"10.0.0.{i}" for i in range(1, 16)]
reviewed = []

for ip in targets:
    last_octet = int(ip.split(".")[-1])

    if last_octet % 2 != 0:
        continue

    reviewed.append(ip)
    print(f"Reviewing: {ip}")

    if ip in blocked_ips:
        print(f"Alert: blocked IP found: {ip}")
        break

print("Reviewed:", reviewed)

3. Limit retry attempts with while

In [ ]:
attempt = 0
max_attempts = 3
service_responded = False

while attempt < max_attempts and not service_responded:
    attempt += 1
    print(f"Health check attempt {attempt}")
    service_responded = attempt == 2

print(f"Service responded: {service_responded}")

4. Package a rule in a function

In [ ]:
def classify_login_risk(failed_attempts, is_admin=False, is_off_hours=False):
    # Return LOW, MEDIUM, HIGH, or CRITICAL for a login event.
    score = failed_attempts * 10
    if is_admin:
        score += 25
    if is_off_hours:
        score += 15

    if score >= 100:
        return "CRITICAL"
    if score >= 60:
        return "HIGH"
    if score >= 30:
        return "MEDIUM"
    return "LOW"


print(classify_login_risk(2))
print(classify_login_risk(7, is_off_hours=True))
print(classify_login_risk(8, is_admin=True))

Self-check

In [ ]:
assert severity == "HIGH"
assert reviewed == ["10.0.0.2", "10.0.0.4", "10.0.0.6", "10.0.0.8", "10.0.0.10", "10.0.0.12"]
assert attempt == 2 and service_responded is True
assert classify_login_risk(2) == "LOW"
assert classify_login_risk(7, is_off_hours=True) == "HIGH"
assert classify_login_risk(8, is_admin=True) == "CRITICAL"
print("✓ Lab 2 completed")

Extension challenge

Modify the function to add 20 points when source_ip belongs to a set of blocked IP addresses. Write at least two assert statements for the new rule.