Files
labs/Lab-2/Lab-2-Practical/02_Control_Flow_Functions_Lab.ipynb

5.1 KiB

Module 2 — Lab 2: Control Flow and Functions

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

Instructions: Run the cells in order. Complete every TODO, then run the Self-check cell. Do not open the Solution notebook before attempting the tasks yourself.

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

# TODO 1: assign severity using the thresholds 10, 5, 1, and 0
severity = None

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])

    # TODO 2: skip IP addresses whose final octet is odd
    pass

    # TODO 3: append the IP address to reviewed
    pass

    # TODO 4: if the IP is in blocked_ips, print an alert and stop the loop
    pass

print("Reviewed:", reviewed)

3. Limit retry attempts with while

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

# TODO 5: loop while max_attempts has not been reached and the service has not responded.
# Simulate the service responding on the second attempt.
while False:
    pass

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.
    # TODO 6: calculate the score and return a label using thresholds 100, 60, and 30
    pass


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.